I'm trying to use Url.Action to call the controller c# function:
public ActionResult Setup(string ID, string Definition)
This function is located in the controller class MachineController.cs, and it returns a PartialView.
So, in with my script, i'm trying to call function 'Setup' with the line:
var selected = $('#dropselector').find(':selected').text();
$.get('#Url.Action("Setup", "Machine", new { ID = #Model.ID , Definition = "_holder"})'.replace("_holder", selected), function (data) {
$('#MachineSetup').replaceWith(data);
});
What seems to happen is the first parameter (ID) is passed no problem, but the second parameter (Definition) is always empty string. I've even tried assigning 'Definition' to #Model.ID same as the ID field as they are both strings, but it just seems to result in the same, ID is populated but Definition is an empty string.
The problem definitely relates to the passing of a second parameter, any ideas?
you could try the following
var selected = $('#dropselector').find(':selected').text();
$.get(
'#Url.Action("Setup","Machine", new { ID = #Model.ID })',
{
data:{definition:selected}
} ,
function (data)
{
$('#MachineSetup').replaceWith(data);
});
as the url will contain the Model.ID but the dynamic value of selected will change.
also if you are doing a Setup would you not consider a POST action to make sure the values are not cached on the client machine.
Related
ActionLink is executing properly but not passing id variable.
This is executed first in my main view
<li>#{ Html.RenderAction("ReviewAverage", "Home", Model.TripId); }</li>
which executes this:
[ChildActionOnly]
public ActionResult ReviewAverage(int? id)
{
Trip trip = db.Trips.Find(id);
List<int> values = trip.Reviews.Select(review => review.Rating).ToList();
double average = values.Average();
ViewData["ReviewAverage"] = average;
return PartialView("_ReviewAverage", id);
}
This is the partial view that above method returns and which doesn't for some reason pass the id = Model even though Model variable is definitely set.
The actionLink below is not passing the id to my controller
#model int
<li>#Model</li>
#Html.ActionLink("Reviews (avg: "+ ViewData["ReviewAverage"] +")", "Reviews", "Home", new { id = Model }))
Which should lead to with that id
public ActionResult Reviews(int? id)
{
Trip trip = db.Trips.Find(id);
List<Review> reviews = trip.Reviews;
return View(reviews);
}
When creating a link to a controller action in ASP.NET MVC, using the generic ActionLink method is preferable, because it allows for strongly typed links that are refactoring friendly. Try this:
#Html.ActionLink("Reviews", "Home", new { id = item.Id })
For more information you might have a look at How do I set a click event in C#?. Hope this helps...
The third parameter of the RenderAction overload is the route values. The method expects a dictionary with key and value. Make sure the key matches your action method parameter.
You can pass an annonymous object with id property (which matches your ReviewAverage action method param name.
#{ Html.RenderAction("ReviewAverage", "Home", new { id= Model.TripId} ); }
Now for your action link, you are using the overload incorrectly, The overload you are using expects the last parameter to be an anonymous object need to build the html attributes(ex : css class/ other html attributes).
You can use the correct overload which takes 5 parameters ( 4th one is route values nd 5th one is htmlAttributes)
#Html.ActionLink("Reviews (avg: "+ ViewData["ReviewAverage"] +")",
"Reviews", "Home", new { id = Model },null))
I´m new to mvc and I try to to do a simple Ajax call to my controller, so I can use a date- and timepickers in my create view.
I get this error message when I use debugging in IE, but if I do a breakpoint it looks like I got correct data.
The parameters dictionary contains a null entry for parameter 'Lokal' of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult CreateEvent(System.String, System.String,
System.String, Int32)' in
'VLVision.Controllers.SammantradesAdminController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter.Parameternamn: parameters
HTML
script type="text/javascript">
function createSammantrade() {
var sammantrade = document.getElementById('sammantrade').value;
var date = document.getElementById('datepicker').value;
var startTime = date + ' ' + document.getElementById('StartTimepicker').value;
var endTime = date + ' ' + document.getElementById('EndTimepicker').value;
var lokal = document.getElementById('lokal').value;
$.ajax({
url: "#Url.Action("CreateEvent", "SammantradesAdmin")",
data: { createSammantrade: sammantrade, createStartTime: startTime, createEndTime: endTime, createLokal: lokal },
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
$("#clanderDiv").html(data);
$("#setEventResponse").html("Händelse sparad");
// $(".blank").tooltip();
}
});
}
Controller
public ActionResult Create()
{
ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal");
return View();
}
[HttpPost]
public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, int Lokal)
{
Sammantrade sammantrade = new Sammantrade();
sammantrade.sSammantrade = createSammantrade;
sammantrade.sStartTid = Convert.ToDateTime(createStartTime);
sammantrade.sSlutTid = Convert.ToDateTime(createEndTime);
sammantrade.lID = Lokal;
if (ModelState.IsValid)
{
db.Sammantrade.Add(sammantrade);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal", sammantrade.lID);
return View(sammantrade);
}
Since you have different names for the parameter in JS and in C#, it cannot be bound:
data: { createSammantrade: sammantrade, createStartTime: startTime, createEndTime: endTime, createLokal: lokal }
public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, int Lokal)
Either change createLokal to lokal in JS or do vice versa in C# (or bind one name to another).
Your parameter name in json is different from the c# action, these two should match. Change one of those:
either change createLokal : lokal to Lokal:lokal or in your action change parameter name to createLokal in your action
Thanks, it did not work at first. But when I debugged it I saw that the result from lokal was a string I change it to a string and then convert it back to a int.
Now I have some other problems, but I think I can fix the rest.
Sry for my crappy English, but I hope you understand what I mean.
Thanks!
I've got a simple action method that lists some data from a repository. The view for this action method uses simple paging. The URL can be clicked on, or entered as server:port/product/2 where 2 is the page number. If the user enters in a page number that's greater than the number of pages of data, I want to redirect the user to server:port/product/1 first and the notify them they were redirected. The redirecting part works, but I can't seem to find a way to get the value passed to the action method.
EDIT: I used QueryString incorrectly in this question, what I really want is the parameter passed to the action method.
ProductController
public ActionResult List(int page =1)
{
ProductsListViewModel model = new ProductsListViewModel();
model.Products = _repository.Products.OrderBy(x => x.ProductId)
.Skip((page -1) * 4)
.Take(4);
model.PagingInfo = new PagingInfo()
{
CurrentPage = page,
ItemsPerPage = 4,
TotalItems = _repository.Products.Count()
};
//this correctly redirects
if (page > model.PagingInfo.TotalPages)
{
return RedirectToAction("List", new { page = 1 });
}
return View(model);
}
JavaScript
var pageParam = "#Request.QueryString["id"]"
var pageTotal = "#Model.PagingInfo.TotalPages";
var pageCurrent ="#Model.PagingInfo.CurrentPage";
console.log('this is the current page: ' + pageCurrent);
console.log(pageTotal);
console.log(pageParam);
function notifyRedirect(pageTotal, pageParam) {
if (pageParam > pageTotal) {
alert('you entered ' + pageParam + ', an invalid page parameter and were redirected');
window.location = '/Product/List/1';
}
}
notifyRedirect(pageTotal,pageParam);
Routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
When the page loads, the pageTotal and pageCurrent variables are printed to the console, but I get an empty string when trying to get the QueryString value. Thinking that maybe I had the name of the parameter wrong, I decided to use the integral index of the QueryString and was presented with the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How is it that http://localhost:49997/product/list/2, the fully qualified URL still gives me an empty QueryString value? How can I use JS to notify the user of the redirect?
Perhaps I'm missing something, but it seems like your question is "How do I get a query string value from a URL without a query string."
Both your redirect URL, /Product/List/1 and your last URL mentioned, http://localhost:49997/product/list/2, have no query string, so any attempt to access anything in Request.QueryString is going to return null.
If you need something in the query string on the redirect then you need to add that to the redirect URL:
window.location = '/Product/List/1' + ((pageParam != '') ? '?id=' + pageParam : '');
Change the parameter name of the action method from page to id to agree with MapRoute. Then you don't need the first MapRoute, if you don't skip the name of the action in the url.
I have a page route with an optional "id" parameter. Defined like so:
routes.MapPageRoute(null,
"projects/{operation}/{id}",
"~/Projects/ProjectWizard.aspx",
true,
new RouteValueDictionary(new
{
operation = "new",
id = UrlParameter.Optional
}),
new RouteValueDictionary(new
{
operation = #"new|edit",
id = #"\d*"
})
);
The route works fine, but when I get to the page if I haven't included the optional "id" parameter then my code fails when trying to convert to integer.
var operation = RouteData.Values["operation"].ToString();
var projectId = RouteData.Values.ContainsKey("id") ? Convert.ToInt32(RouteData.Values["id"]) : 0;
This works great as long as I pass in an ID in the route like this:
http://webapp/projects/edit/123
projectId is equal to 123 just like it should be. But if I don't include the ID:
http://webapp/projects/new
The route goes to the page fine but I get this error:
Unable to cast object of type 'System.Web.Mvc.UrlParameter' to type 'System.IConvertible'.
It should be unable to find the key in the route data values and then assign a zero to projectId, but it doesn't. I keep trying different ways to check for null for the "id" route value but it doesn't seem to like that very much.
That would work perfectly were you dealing with MVC controller actions here and MapRoute.
What I would do in your case is simply set the default for your id in the defaults instead of UrlParameter.Optional, so:
routes.MapPageRoute(null,
"projects/{operation}/{id}",
"~/Projects/ProjectWizard.aspx",
true,
new RouteValueDictionary(new
{
operation = "new",
id = "0"
}),
new RouteValueDictionary(new
{
operation = #"new|edit",
id = #"\d*"
})
);
then simply read your id like so:
var operation = RouteData.Values["operation"].ToString();
var projectId = int.Parse(RouteData.Values["id"].ToString());
I'm trying to send selected checkbox values to another asp page to update database.
$("#Delete_selected_Comment_button").click(function () {
var dataToBeDeleted = new Array();
$('.checkboxes_to_delete:checked').each(function (key, value) {
dataToBeDeleted .push($(this).val());
});
$.ajax({
url: 'http://myurl.aspx',
type: 'GET',
data: dataToBeDeleted,
success: function () { alert('yipee'); },
error: function () { alert("Ooff could not delete data"); }
});
});
Problem:
I am not able to retrieve any value in myurl.asp page.
I am doing:
String datagotfromajax= request.QueryString[dataToBeDeleted];
Am doing this incorrectly? Where is my mistake ? Can anyone help please?
An easy way would be to change one line:
data: "ids="+dataToBeDeleted.join(","),
And, in the server do:
string[] ids = Request.QueryString["ids"].ToString().Split(",");
With this you'll hava a string array in the server with the corresponding checkboxes values.
HOpe this helps.
dataToBeDeleted will be converted to a query string (if its not already) when sent to the server, that means it consists key-value pairs, i.e. foo=bar&fred=fish. On the server you can query individual key-value pairs using the syntax
string bar = request.QueryString["foo"];
You are passing an array as the data parameter. This won't work. You need to pass an object. If the object contains an array, this will be serialized appropriately. This means your code should probably look like this:
data: {
toBeDeleted: dataToBeDeleted
},
This will then be serialized appropriately (see $.param for the serialization process) and you can retrieve the values with your back-end code.