c# - 将表单数据发送到 ASP.net MVC 3 中的 Controller 操作有哪些不同的方法?

标签 c# asp.net-mvc forms asp.net-mvc-3 http-post

我想发布一个具有网格布局的表单数据,每行中的一列包含下拉列表。下拉列表中的选定值映射到该行的项目 ID。

我想知道在这种情况下将此数据发布到 Controller 操作的不同方式有哪些?

作为单个参数传递已被忽略选项,因为我的表单将包含动态数据并且它可能有 n 条记录。我的这种想法是否正确?

想到FormCollection,这个选择对吗?

最佳答案

一如既往,我会先定义一个 View 模型:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

然后有一个 GET Controller 操作,它将填充此 View 模型的集合,并在相应的 View 中使用编辑器模板:

@model IEnumerable<MyViewModel>
@using (Html.BeginForm())
{
    <table>
        <thead>
            <tr>
                <th>Some column name</th>
            </tr>
       </thead>
        <tbody>
            @Html.EditorForModel()
        </tbody>
    </table>

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

并在相应的编辑器模板中(~/Views/Shared/EditorTemplates/MyViewModel.cshtml):

@model MyViewModel
<tr>
    <td>
        @Html.DropDownListFor(
            x => x.SelectedValue,
            new SelectList(Model.Values, "Value", "Text")
        )
    </td>
</tr>

最后这将发布选定的值:

[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
    ...    
}

关于c# - 将表单数据发送到 ASP.net MVC 3 中的 Controller 操作有哪些不同的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867232/

相关文章:

php - MySQL 查询不是通过 PHP 提交而是作为原始查询提交

java - 连接json-rpc接口(interface)

c# - 如何将组合框的选定值转换为整数?

asp.net-mvc - knockout 数组过滤器和计算可观察值不起作用

.net - 在 Visual Studio 2008 中部署 ASP.NET MVC 应用程序

ruby-on-rails - 用于创建和更新的 DRY 表单部分

c# - 将 Windows 按键发送到应用程序

c# - Miniprofiler 中的渲染步骤发生了什么?

javascript - 如何使用存储在 session 存储中的访问 token 通过 HttpClient 进行 Web api 调用?

javascript - 从表单中检索值