I’m trying to auto submit on dropdownlist change to my controller with arguments. The POST does happen but I only get this error
The parameters dictionary contains a null entry for parameter ‘category’ of non-nullable type ‘System.Int32’ for method ‘System.Web.Mvc.ViewResult Index(System.String, System.String, Int32)’ in ‘shopping.WebUI.Controllers.HomeController’. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
I have a JQuery script
$(".autoSubmit select").change(function () {
$(this).closest('form').submit();
});
a form on my View
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.Action("ShipToCountry", "Filters", new { Model.SelectedCountry })
}
but need to POST to this action
[HttpPost]
public ViewResult Index(string country, string currency, int category)
{
var viewModel = new MainViewModel
{
SelectedCountry = country,
SelectedCurrency = currency,
Categories = category }
};
return View(viewModel);
}
None of the country, currency, category arguments is or can be optional.
What changes do I need to make, on the View maybe, to pass those parameters to the Action?
Thanks
The error states that your
categoryparameter ofIndexview is NULL. You either have to change the HTML and javascript so that thecategoryparameter gets value before posting or you can change the POST method to makecategoryoptional like this:EDIT:
Since you can’t make parameters optional, you have to ensure in your HTML that before doing the POST, all
<input>and<select>elements are correctly filled (and correctly named if they already aren’t).In your case, the problem is with the category parameter. Assuming that the select that auto-submits is also the dropdown list of categories, you need to assure that the outputted HTML is similar to this:
The key here is that select MUST have the name
category(or you should rename the parametercategoryin theIndexmethod to match the name of this select) and that options MUST have integer values.EDIT 2:
To add the currency and category, you need to add
<input name="currency">and<input name="category">fields to the same<form>where your country is. Note, that it doesn’t need to be<input>specifically, it could be<select>as well, but the field’snamemust be the same as the name of parameters inIndexmethod.