2012-11-12 107 views
0

我有一組PartialView在頁面中動態更改。 PartialView使用ajax加載下一個等等。其中一個有20個輸入的形式,目前我只是發送一個輸入,但我怎樣才能發送剩餘的輸入?我有這個在此partialview:使用Ajax發送數據到控制器 - MVC 3剃鬚刀

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是新和剃刀

感謝

回答

1

使用JSON模型綁定。 This post可以幫助你獲得照片。

總之,創建JavaScript對象與屬性名稱匹配模型。將它發送給控制器,它將被綁定。另請注意,數字最好以字符串形式發送(look at this)。

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 
}