0

我有一组在页面中动态更改的 PartialView。PartialView 使用 ajax 加载下一个,依此类推。其中一个有 20 个输入的形式,目前我只发送一个输入,但我怎样才能发送其余的输入?我在这个部分视图中有这个:

var shipping= $("input[name='shipping']:checked").val()
    $.ajax(
      {
          url: '/Home/Payment',
          type: "POST",
          data: { 'shipping': shipping},
          success: function (data) {
              $("#cart").html(data);

          }
      });

这在控制器中:

public ActionResult Payment(string shipping)
    {
        **do stuff*
        return PartialView("NextPartialView");
    }

控制器接收表单的每个输入,但正如我之前所说的,其中有 20 个。有没有办法使用另一种技术发送数据来保持代码的清洁和可读性?

我是 MVC 和 razor 的新手

谢谢

4

2 回答 2

1

使用 JSON 模型绑定。 这篇文章可以帮助您了解图片。

简而言之,创建属性名称匹配模型的 javascript 对象。将其发送给控制器,它将被绑定。另外,请注意,数字最好作为字符串发送(看看这个)。

于 2012-11-12T01:47:24.920 回答
0

将您的项目放在表单中并序列化表单并发送到操作方法。

@model YourSomeViewModel
@using(Html.Beginform())
{
  FirstName :   @Html.TextBoxFor(x=>x.FirstName)
  LastName:   @Html.TextBoxFor(x=>x.LastName)
  Location :   @Html.TextBoxFor(x=>x.Location)
  Is Available to hire @Html.CheckBoxFor(x=x.IsAvailable)
  <input type="submit" id="btnSubmit" />
}

现在在你的脚本中

$(function(){
  $("#btnSubmit").click(function(e){
    $.post("@Url.Action("Save","YourControllerName")", 
                          $(this).closest("form").serialize(), function(data){
            //do something with the response
    });    
  });  
});

现在您的操作方法参数将成为您的视图模型类。Mvc 模型绑定会将发布(序列化)的表单数据映射到您的视图模型类的实例。

[HttpPost]
public ActionResult Save(YourSomeViewModel model)
{
   //check model properties now

  //saved and respond /redirect
}
于 2012-11-12T02:03:29.003 回答