Asp.net mvc 3 将我的表格绑定到模型上

Asp.net mvc 3 将我的表格绑定到模型上,asp.net-mvc-3,Asp.net Mvc 3,我有一个ViewModel,其中包含我的模型列表,如下所示: public class OrderConfirm { public ICollection<DayBookQuoteLines> SalesLines { get; set; } public ICollection<DayBookQuoteLines> LostLines { get; set; } public string Currency { get; set; } } 因此

我有一个ViewModel,其中包含我的模型列表,如下所示:

public class OrderConfirm
{
    public ICollection<DayBookQuoteLines> SalesLines { get; set; }
    public ICollection<DayBookQuoteLines> LostLines { get; set; }
    public string Currency { get; set; }
}

因此,
quoteLines
为空。如何将表单绑定到我的模型?

表单中没有任何将值发送到服务器的输入字段。您只是在显示它们。这就是为什么当您提交表单=>时,它们是空的,不会向服务器发送任何内容

但是,如果在该表单中,用户不应该修改任何值,那么您需要做的就是将id传递给控制器操作,该操作将允许您从呈现该表单的GET操作中获取模型的同一位置获取模型

在这种情况下,您的操作如下所示:

[HttpPost]
public ActionResult ConfirmSalesOrder(int id)
{
    List<DayBookQuoteLines> quoteLines = ... fetch them the same way as in your GET action
    // Process order...

    return PartialView("Sales/_ConfirmSalesOrder");
}
然后对表单进行AJAXify:

$('#formId').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        contentType: 'application/json',
        data: JSON.stringify({ quoteLines: model }),
        success: function(result) {
            $('#someTargetIdToUpdate').html(result);
        }
    });
    return false;
});

问题是,我在GET请求中获取它们的方式是将它们保存在TempData中,因为我还没有向数据库提交任何更改,因为视图是一种确认页面,一旦单击Submit,就会将更改提交到数据库。在这种情况下,您必须为要保留的每个属性提供隐藏字段。最好的方法是在整个编辑器模板中执行此操作,以确保为这些隐藏字段生成专有名称。没有奇迹。HTTP协议本质上是无状态的。也可能有人建议您使用会话而不是TempData。就我个人而言,我不会使用它,也不会推荐它。我已经用另一种你可以使用的技巧更新了我的答案。它包括将模型序列化为javascript变量,您可以在发送AJAX请求时将该变量重新传递给控制器操作。
[HttpPost]
public ActionResult ConfirmSalesOrder(int id)
{
    List<DayBookQuoteLines> quoteLines = ... fetch them the same way as in your GET action
    // Process order...

    return PartialView("Sales/_ConfirmSalesOrder");
}
<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>
$('#formId').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        contentType: 'application/json',
        data: JSON.stringify({ quoteLines: model }),
        success: function(result) {
            $('#someTargetIdToUpdate').html(result);
        }
    });
    return false;
});