你是如何处理在ASP.NET MVC中动态生成的形式输出? [英] How do you handle the output of a dynamically generated form in ASP.NET MVC?

查看:119
本文介绍了你是如何处理在ASP.NET MVC中动态生成的形式输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你使用ASP.NET MVC具有表单元素的动态数创建一个表单。

Say you create a form using ASP.NET MVC that has a dynamic number of form elements.

例如,你需要为每个产品一个复选框,产品数量每天变换。

For instance, you need a checkbox for each product, and the number of products changes day by day.

您将如何处理表单数据被调回控制器?你不能建立在行动方法的参数,因为你不知道很多形式值是如何将要回来。

How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.

推荐答案

只要给每个复选框的唯一名称值:

Just give each checkbox a unique name value:

<input class="approveCheck" id="<%= "approveCheck" + recordId %>" 
 name="<%= "approveCheck" + recordId %>" type="checkbox" />

然后解析的形式行动值列表,之后提交:

Then parse the list of form values in the Action, after submit:

foreach (var key in Request.Form.Keys)
    {
        string keyString = key.ToString();
        if (keyString.StartsWith("approveCheck", StringComparison.OrdinalIgnoreCase))
        {
            string recNum = keyString.Substring(12, keyString.Length - 12);

            string approvedKey = Request.Form["approveCheck" + recNum];
            bool approved = !String.IsNullOrEmpty(approvedKey);
            // ...

您并不需要通过表单值作为参数;你可以从刚刚得到的Request.Form他们。

You don't need to pass form values as arguments; you can just get them from Request.Form.

另外一个选择:写一个模型绑定更改列表成表单提交的自定义类型

One other option: write a model binder to change the list into a custom type for form submission.

这篇关于你是如何处理在ASP.NET MVC中动态生成的形式输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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