Problem I want my Ajax form to pass the value of the selected DropDownListFor to the controller but I can't figure out why the controller is not taking any value. I am working with ASP.NET MVC and I would like to stick with the helper functions as much as I can.
View
@using (Ajax.BeginForm(new AjaxOptions {
HttpMethod = "Get",
UpdateTargetId = "UserResults",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace }))
{
@Html.DropDownListFor(Model => Model.Roles, new SelectLi(ViewBag.Groups
as System.Collections.IEnumerable, "Value", "Text"), "Select a group",
new { id = "Value", onchange = "$(this.form).submit();" })
}
@Html.Partial("_UsersGroup", ViewData)
Controller
public ActionResult test(int? selectGroup)
{
// Generate dropdownlist Groups
List<SelectListItem> groupList = new List<SelectListItem>();
var query = from s in db.Roles select s;
if (query.Count() > 0)
{
foreach (var v in query)
{
groupList.Add(new SelectListItem { Text = v.Name, Value =
v.ID.ToString() });
}
}
ViewBag.Groups = groupList;
// End
// This part is supposed to take the passed value as parameter
if (selectGroup == null)
{
// To do code comes here, which takes selectGroup as parameter
}
Details
The form should pass a value based on the selection to the controller which takes it as "selectGroup".
ps. this is my first time asking a question, I'm sorry if I made mistakes.
The parameter of you method needs to match the name of the control which is name="Roles"
so the method should be
public ActionResult test(int? roles)
Other potential issues with your code
Your controller generates List<SelectListItem>
for use by the dropdownlist. There is no need for the unnecessary extra overhead of then creating a new SelectList
(which is IEnumerable<SelectListItem>
) from it. The view code can simply be @Html.DropDownListFor(m => m.Roles, (IEnumerable<SelectListItem>)ViewBag.Groups, "Select a group")
Do not use Model
(capital M) in the expression. If you make any other reference to the model in your view (e.g. @Model.SomeProperty
) you will get an error. Using lower case model => model.somProperty
is OK but you can simply use m => m.someProperty
The helper will generate an id
attribute (in you case id="Role"
) so it seems unclear why you are adding new { id = "Value", ..}
, especially since you don't appear to be referencing the element by its id
anywhere
Learn to use Unobtrusive Javascript rather than polluting you mark up with behavior. Remove the onclick
attribute and use $('#Roles').change(function() { $('form').submit(); });