1

I'm building a simple form with a dropdown and a submit button.

@using(Html.BeginForm("Index", "Account", FormMethod.Post))
{
    @Html.DropDownList(
        "Roles",
        new SelectList(new List<string> { "User", "Manager", "Chuck Norris" }),
        new { id = "role", name="role" })

    <input type="submit" value="Update" />
}

And my controller looks like this:

[HttpPost]
public ActionResult Index(string role) <-- role is null when clicking submit
{
}

I was kinda hoping the value from the dropdown would automatically be injected as parameter of my controller method, but this is not the case. Am I missing something or is it simply not possible to do it like this?

3
  • 2
    Your generating a <select> with name="Roles" but your parameter is named role (not plural). Change one or the other. (attempting to use name = "role" is ignored by the method - fortunately) Commented May 26, 2016 at 12:41
  • What is the resulting HTML that this creates? Commented May 26, 2016 at 12:41
  • @StephenMuecke Please make that an answer and I'll accept it. Commented May 26, 2016 at 12:44

2 Answers 2

2

Your generating a <select> element with name="Roles" but the parameter of your method is named role (not plural). You need to change one or the other so that they match (note that the DefaulModelBinder is not case sensitive, so the parameter can be roles or ROleS)`

Note that setting new { name = "role" } does not change the name attribute generated by the HtmlHelper method. It should also not be necessary to use name { id = "role" } - the method already generates id="Roles" so if you are referencing the element using javascript/jquery, then just use $(#Roles') as the selector

Sign up to request clarification or add additional context in comments.

Comments

0

Change role to Roles like the code below

public ActionResult Index(string role)

to

public ActionResult Index(string Roles)

now it will work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.