I am trying to use Url.Action to generate the correct HTTP URL based on a controller action like this :
$.post('#Html.Raw(Url.Action("Delete", new { id = "1" }))')
However, it is not working as expected . The actual url fired (got this from dev tools) is
http://localhost:60223/CordBlood/#Html.Raw(Url.Action(%22Delete%22,%20new%20%7B%20id%20=%20%224%22%20%7D))
Whereas I want something like this :
http://localhost:60223/CordBlood/Delete/1
What am I doing wrong here?
I think you are trying to achieve something similar to this
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#dropdown").change(function () {
var id = $("#dropdown").val();
if (id == "")
{ id = 0; }
var dataToSend = {
Id: id
};
RedirectToPage(id);
});
function RedirectToPage(id) {
var url = '#Url.Action("Delete", "yourController", new { Id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
});
</script>
Hope this will give you some idea
Related
i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically.
this is the code that i wrote in the view and i have a compilation error in that line at runtime:
#Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"})
"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .
public ViewResult FilterdIndex(int id)
{
var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
select new
{
BG.GROUP_ID,BG.GROUP_NAME,
Checked=(BG.GROUP_ID==id)
};
ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
return View(donor.ToList());
}
this is javascript code it executes the controller function correctly but i don't know why after returning to the view i have the error msg in this line :
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
and this is the whole function:
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
if ($("#DONOR_BLOOD_GROUPE_ID").val() != "Select") {
var DONOR_BLOOD_GROUPE = {};
DONOR_BLOOD_GROUPE.url = '#Url.Action("FilterdIndex", "DONOR")';
DONOR_BLOOD_GROUPE.type = "POST";
DONOR_BLOOD_GROUPE.data = JSON.stringify({ id: $("#DONOR_BLOOD_GROUPE_ID").val() });
DONOR_BLOOD_GROUPE.datatype = "html";
DONOR_BLOOD_GROUPE.contentType = "application/json";
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
$.ajax(DONOR_BLOOD_GROUPE);
}
});
});
</script>
and this is the line that causes the exception in "DONOR[dynamic]" file
<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>
I assume you come from a WebForms background where this sort of thing happens all the time with 'Events' this sadly is not how MVC works.
To do what you are trying to do, you will need to create a jquery method for the onchange event of that drop down, then do an async post to your controller.
Have a look at this tutorial which should point you in the right direction
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Hi Asmaa Rashad you can try using this way and your action Method which you are calling using Ajax must be of type JsonResult.
<script type="text/javascript">
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("FilterdIndex", "DONOR")',
dataType: 'json',
data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
success: function (data) {
},
error: function (ex) {
alert('Failed to retrieve + ex);
}
});
return false;
})
});
</script>
For reference you can check this blog creating-simple-cascading-dropdownlist-in-mvc-4-using-razor
I need to be able to populate data into a <div> or some other sort of section from an object after the corresponding string has been selected from a drop down list (lazy loading).
When a chnage is made in the dropdownlist, I want the method in my controller to be called which will fill in <div id=result></div> with the output from the method.
Perhaps I am approaching this problem wrong.
I suspect the problem is in my JavaScript.
Here is my approach:
View:
<div>#Html.DropDownList("MyDDL") </div>
<br>
<div id="result"></div>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = "";
$("#MyDDL option:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "HomeController/showInfo";
//I suspect this is not completely correct:
$.post(url, {str: strSelected},function (result) {
$("result").html(result);
});
});
});
</script>
Controller (Perhaps I shouldn't be using PartialViewResult):
public ActionResult Index()
{
List<string> myList = new List<string>();
List<SelectListItem> MyDDL = new List<SelectListItem>();
myList.Add("Tim");
myList.Add("Joe");
myList.Add("Jim");
//fill MyDDL with items from myList
MyDDL = myList
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
ViewData["MyDDL"] = MyDDL;
return View();
}
[HttpPost]
public PartialViewResult showInfo(string str)
{
Person p = new Person(str); //name is passed to constructor
p.LoadInfo(); //database access in Person Model
ViewBag.Info = p.Info;
return PartialView("_result");
}
_result.cshtml:
<p>
#ViewBag.Info
</p>
Thanks You.
Change your script a little bit. Missing a # in the jQuery selecter for result div . Use the code given below
$.post(url, {str: strSelected},function (result) {
$("#result").html(result);
});
In my opinion if the javascript are in local don't need put $.post(url, {str: strSelected},function (result) {
You can use
//I suspect this is not completely correct:
$("#result").html(result);
try it
Did you try debugging p.LoadInfo() if it has any value? I also have some suggestions for your script:
Try adding keyup in your event so you can get the value in cases when the arrow keypad is used insted of clicking:
$("#MyDDL").on("change keyup", function () {
// you can get the dropdown value with this
var strSelected = $(this).val();
So I made the following changes and it worked:
View:
<div><%= Html.DropDownList("MyDDL") %> </div>
<br>
<span></span>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = $("#MyDDL option:selected").text();
var url = "/Home/showInfo";
$.post(url, {str: strSelected},function (result) {
$("span").html(result);
});
});
});
_result.cshtml:
#ViewBag.Info
The Controller was left unchanged.
$(document).ready(function ()
{
$(".viewmap").click(function ()
{
var id = $(this).attr("id");
var responseURL = "~/changemap?id=" + id;
//alert(responseURL);
$.ajax(
{
url: responseURL,
dataType: "json",
type:"GET",
success: function (dt)
{
initialize(dt.Latt, dt.Longt);
}
}
);
}
);
});
I use that script to make an ajax call to the page changemap.cshtml which does the following
#{
if(!IsPost)
{
if(!Request.QueryString["id"].IsEmpty()&&Request.QueryString["id"].IsInt())
{
var countryId=Request.QueryString["id"];
var db=Database.Open("GoogleMapView");
var dbCmd="SELECT * FROM places WHERE id=#0";
var row=db.QuerySingle(dbCmd,countryId);
if(null!=row)
{
Json.Write(row,Response.Output);
}
}
}
}
That is to return the queried data from the database in json format to the client. The Initialize function is defined as
function initialize(lat,lng)
{
var mapOptions = {
center: new google.maps.LatLng(lat,lng),zoom: 8,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"),mapOptions);
}
But when I click the div tag of class viewmap, nothing happens. I think I miss some more script to get my application to work correctly.
I only try to implement a simple google map view in which once the user clicks a place name as a hyperlink will reload the map that matches with it.
I think
var responseURL = "~/changemap?id=" + id;
should be
var responseURL = '#(Url.Content("~/changemap")+"?id=")' + id;
try thr following
success(data){
initialize(data.d.Latt, data.d.Longt);
}
for more reference as in why d is used check the following link
http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/
I have a partial view that I am calling on pages as follows :-
#Html.Partial("~/Views/Shared/ImageGallery.cshtml", Model)
The code for the actual Jquery of this page is a s follows :-
<script type="text/javascript">
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var context = $('#tn_select').load('/Upload/UploadImage?Page=Article&Action=Edit&id=16', function () {
initSelect(context);
});
e.preventDefault();
return false;
});
});
</script>
Now this works perfectly, however I need to find a way to pass dynamic vars instead of hard coded vars to this :-
Upload/UploadImage?Page=Article&Action=Edit&id=16
In the Model I have all the vars, however I do not know how I can insert them into the Jquery. Any help would be very much appreciated!
---------UPDATE-----------------------
This is the code I am putting into each cshtml that needs the ImageGallery.
</div>
#Html.HiddenFor(model => model.PageViewModel.Page.PageTitle, new { id = "PageTitle"});
#Html.HiddenFor(model => model.PageViewModel.Page.PageAction, new { id = "PageAction"});
#Html.HiddenFor(model => model.ArticleViewModel.Article.ArticleID, new { id = "ArticleID"});
<div>
#Html.Partial("~/Views/Shared/ImageGallery.cshtml", Model)
</div>
New Javascript in the ImageGallery :-
<script type="text/javascript">
var pageTitle = $('#PageTitle').val();
var pageAction = $('#PageAction').val();
var id = $('#ArticleID').val();
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var context = $('#tn_select').load('/Upload/UploadImage?Page=' + pageTitle + '&Action=' + pageAction + '&id=' + id, function () {
initSelect(context);
});
e.preventDefault();
return false;
});
});
</script>
This works fine now
You can add hidden field to your view and bind data form the model. Then you can easily read this value from jQuery.
View:
#Html.HiddenFor(model => model.Id, new { id = "FieldId"});
Script:
var id= $('#FieldId').val();
Also you can put this hiddens into your partial view. If your partial view is not strongly typed change HiddenFor to Hidden. Your ImageGallery partial view should contain the following div:
</div>
#Html.Hidden("PageTitle", Model.PageViewModel.Page.PageTitle);
#Html.Hidden("PageAction", Model.PageViewModel.Page.PageAction);
#Html.Hidden("ArticleID", Model.ArticleViewModel.Article.ArticleID);
<div>
In this case you don't need to put hiddens to every cshtml that needs the ImageGallery.
You can either set hidden fields or just declare javascript variables and set their values from either your model or the Viewbag, just like:
var action = #Model.action;
or
var id = #ViewBag.id;
and you can just use it in your code
<script type="text/javascript">
var action = #Model.action;
var id = #ViewBag.id;
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var urlToLoad = "/Upload/UploadImage?Page=Article&Action=" + action + "&id=" + id;
var context = $('#tn_select').load(urlToLoad, function () {
initSelect(context);
});
e.preventDefault();
return false;
});
});
The following is another solution. I was in need of passing my api url declared in web.config to JavaScript (in this case Jquery)
In Razor declare a variable
#{var apiUrl= #System.Configuration.ConfigurationManager.AppSettings["BlogsApi"];}
Then in JavaScript
var apiUrl = '#apiUrl';
This is driving me crazy. All I'm trying to do is to pass in a Id to a ActionMethod which is working and have an Object be returned to the javascript. Then in javascript, I want to be able to say something like..Objec.Property, ie/ Student.Name, or Student.GPA.
Any help is appreciated. I tried json but couldn't get that to work either.
ActionResult:
[AcceptVerbs(HttpVerbs.Get)]
public Epic GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id));
return Epictemplist.SingleOrDefault();
}
javascript:
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result);
});
});
});
</script>
result.Name is obviously wrong I just dont know how to call this the right way.
Tman, I had a similiar issue that Darin helped me with. I needed to add a $.param to my getJSON. Check out this post MVC ListBox not passing data to Action
try changing your method like this
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id)).SingleOrDefault();
return Json(Epictemplist, JsonRequestBehavior.AllowGet);
}
Than from your JS
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result.Name);
}, 'json');
});
});
</script>