Question

I've just started a new MVC project and I'm having trouble getting the post result from a 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 drop down list appears just fine but I can't see to get the ActionResult Test function to run. I thought it would just bind itself with reflection but whatever is wrong, I can't see it.

Was it helpful?

Solution

You have two main errors in your code.

  1. As Brett said you're posting to the Index method, but you don't have Index method that supports POST verb. The easiest way to fix is to change Html.BeginForm() with Html.BeginForm("Test", "TestModel")
  2. You're using Html.DropDownListFor in a wrong way. You could pass only a value types there, because don't forget that the View will generate an HTML page. So instead of User in your Model you should have an UserID and in your View you should have @Html.DropDownListFor(x => x.UserID, @Model.listSelection). And finally in your Action you should query your data source to get the details for the user with this ID.

Hope this helps.

OTHER TIPS

Looks like you're posting back to index. Either use a GET Test() action method, or specify the ACTION parameter in BeginForm().

For example,

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

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

Or use a view named Test (rename index.cshtml to test.cshtml):

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

    return View(model);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top