【问题标题】:When using strongly typed viewmodels, is it possible to post back checkbox values not in the viewmodel?使用强类型视图模型时,是否可以回发不在视图模型中的复选框值?
【发布时间】:2011-03-11 07:42:04
【问题描述】:

我对 .net 还很陌生。 我使用强类型视图模型。我有一个一般性问题:是否可以在视图中添加复选框(或按钮)而不将它们添加到视图模型并访问控制器操作中的值(选中或未选中)?如果是这样,请解释如何。方法必须贴出来吗? 谢谢

【问题讨论】:

  • 当然,只需将参数添加到 Action Method,或者最坏的情况,直接转到 FormCollection(或 MVC 3 中调用的任何内容)。

标签: asp.net-mvc-3 viewmodel


【解决方案1】:

您始终可以通过以下方式获取表单数据:

Request.Form["FieldName"]

或者将它们作为参数添加到回发 Action 方法中:

[HttpPost]
public ActionResult Edit(MyModel modelData, string extraField) {

但是为什么不将它们添加到您的模型中,如果想要使用它来纠正验证错误,这将变得容易得多。

【讨论】:

    【解决方案2】:

    我真的不明白您所说的在视图中添加复选框而不将它们添加到视图模型中是什么意思,但让我试着用一些例子来说明:

    假设你有以下表格:

    <a href="#" id="add">Add checkbox</a>
    
    @using (Html.BeginForm())
    {
        <div id="placeholder"></div>
        <input type="submit" value="OK" />
    }
    
    <script type="text/javascript">
        var index = 0;
        $('#add').click(function () {
            $('#placeholder').append(
                $('<input/>', {
                    type: 'checkbox',
                    name: 'foo[' + index + ']',
                    value: 'true'
                })
            ).append(
                $('<input/>', {
                    type: 'hidden',
                    name: 'foo[' + index + ']',
                    value: 'false'
                })
            );
            index++;
            return false;
        });
    </script>
    

    还有一个控制器会收到 POST 表单:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpPost]
        public ActionResult Index(IEnumerable<bool> foo)
        {
            // When you submit the form this action will be invoked
            // and you will get an list of boolean values corresponding
            // to each checkbox state
            return View();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多