How to get a strongly typed DropDownList to bind to an Action control

I just started a new MVC project and I am having trouble getting the result after the form.

This is my model class:

public class User
{
    public int id { get; set; }

    public string name { get; set; } 
}

public class TestModel
{
    public List<User> users { get; set; }
    public User user { get; set; }
    public SelectList listSelection { get; set; }

    public TestModel()
    {
        users = new List<User>()
        {
            new User() {id = 0, name = "Steven"},
            new User() {id = 1, name = "Ian"},
            new User() {id = 2, name = "Rich"}
        };

        listSelection = new SelectList(users, "name", "name");
    }
}

This is my view class.

@model MvcTestApplicaiton.Models.TestModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.user, @Model.listSelection)

    <p>
        <input type="submit" value="Submit" />
    </p>
}

@if (@Model.user != null)
{
    <p>@Model.user.name</p>
}

And this is my controller:

public class TestModelController : Controller
{
    public TestModel model;
    //
    // GET: /TestModel/

    public ActionResult Index()
    {
        if(model ==null)
            model = new TestModel();

        return View(model);
    }

    [HttpPost]
    public ActionResult Test(TestModel test)
    {
        model.user = test.user;

        return RedirectToAction("index", "TestModel");
    }

}

The dropdown list is displayed just fine, but I do not see to run the TestResult Test function. I thought that it would just connect itself with reflection, but something is wrong, I do not see it.

+3
source share
2 answers

There are two main errors in the code.

  • , Index, Index, POST-. - Html.BeginForm() Html.BeginForm( "Test", "TestModel" ).
  • Html.DropDownListFor . , , HTML-. User UserID, @Html.DropDownListFor(x = > x.UserID, @Model.listSelection). , , , .

, .

0

, . GET Test() ACTION BeginForm().

,

@using (Html.BeginForm("Test", "TestModel"))
{
    @Html.DropDownListFor(x => x.user, @Model.listSelection)

    <p>
        <input type="submit" value="Submit" />
    </p>
}

Test ( index.cshtml test.cshtml):

public ActionResult Test()
{
    if(model ==null)
        model = new TestModel();

    return View(model);
}
0

All Articles