如何使用ASP.NET MVC多个表单元素 [英] How to use multiple form elements in ASP.NET MVC

查看:133
本文介绍了如何使用ASP.NET MVC多个表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我新的ASP.NET MVC和我想创建为一个集合中的每个项目的文本框中的视图。我怎么做,我该如何捕获的信息时,它会回?我已经使用表格和表格元素构建一个模型静态形式,但从来没有基于可变大小集合动态生成的表单元素。

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 POSTs back? I have used forms and form elements to build static forms for a model, but never dynamically generated form elements based on a variable size collection.

我想要做这样的事情在MVC 3:

I want to do something like this in mvc 3:

@foreach (Guest guest in Model.Guests)
{
    <div>
        First Name:<br />
        @Html.TextBoxFor(???) @* I can't do x => x.FirstName here because
                                 the model is of custom type Invite, and the
                                 lambda wants to expose properties for that
                                 type, and not the Guest in the foreach loop. *@
    </div>
}

我该怎么办每位客人一个文本框?我如何捕捉它们,它回传的操作方法?

How do I do a text box for each guest? And how do I capture them in the action method that it posts back to?

感谢您的帮助。

推荐答案

绝对是一个编辑模板的工作。所以,在你看来,你把这个单行:

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

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

和相应的编辑模板内(〜/查看/共享/ EditorTemplates / Guest.cshtml

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

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

这就是所有。

现在以下措施将工作开箱:

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<Guest> Guests { get; set; }

编辑模板应该叫 Guest.cshtml 。它会自动被调用的客人的每一个元素收集等,当你回来后一切自动工作将采取的正确生成ID和你输入名字照顾。

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.

结论:每次你写一个循环(对于 的foreach )的ASP.NET MVC里面查看您应该知道你做错了,并且有更好的办法。

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.

这篇关于如何使用ASP.NET MVC多个表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆