How to use multiple form elements in ASP.NET MVC

后端 未结 2 2032
刺人心
刺人心 2020-12-03 03:39

So I am new to ASP.NET MVC and I would like to create a view with a text box for each item in a collection. How do I do this, and how do I capture the information when it PO

2条回答
  •  渐次进展
    2020-12-03 04:42

    Definitely a job for an editor template. So in your view you put this single line:

    @Html.EditorFor(x => x.Guests)
    

    and inside the corresponding editor template (~/Views/Shared/EditorTemplates/Guest.cshtml)

    @model AppName.Models.Guest
    
    First Name:
    @Html.TextBoxFor(x => x.FirstName)

    And that's about all.

    Now the following actions will work out of the box:

    public ActionResult Index(int id)
    {
        SomeViewModel model = ...
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Index(SomeViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        // TODO: do something with the model your got from the view
        return RedirectToAction("Success");
    }
    

    Note that the name of the editor template is important. If the property in your view model is:

    public IEnumerable Guests { get; set; }
    

    the editor template should be called Guest.cshtml. It will automatically be invoked for each element of the Guests collection and it will take care of properly generating ids and names of your inputs so that when you POST back everything works automatically.

    Conclusion: everytime you write a loop (for or foreach) inside an ASP.NET MVC view you should know that you are doing it wrong and that there is a better way.

提交回复
热议问题