2009-10-05 31 views
40

在使用以下代碼進行自動刷新時,我假定當我發佈帖子時,模型會自動發送到控制器:

$.ajax({ 
    url: '<%=Url.Action("ModelPage")%>', 
    type: "POST", 
    //data: ?????? 
    success: function(result) { 
     $("div#updatePane").html(result); 
    }, 

    complete: function() { 
    $('form').onsubmit({ preventDefault: function() { } }); 

    } 
}); 

每當有一個帖子,我需要增加在模型中的價值屬性:

public ActionResult Modelpage(MyModel model) 
    {     
     model.value = model.value + 1; 

     return PartialView("ModelPartialView", this.ViewData); 
    } 

但是,當頁面是否使用jQuery AJAX請求模型不傳遞給控制器。我如何在AJAX請求中發送模型?

+0

已經回答了,它幫助我...看看@

回答

2

我想你需要顯式傳遞數據屬性。一種方法是使用 data = $('#your-form-id')。serialize();

這個帖子可能會對您有所幫助。 Post with jquery and ajax

看一看這裏的文檔.. Ajax serialize

+0

我想通過模型不僅僅是表單數據 – ravikiran

+2

當您在接受適當模型的動作上使用form.serialize()時,映射會自動完成。所以,在你的情況下,當你提出這個請求時,「MyModel」實例將被填充表單值。 –

4

我從一組單選按鈕提交選擇值的JSON的MVC頁。

我用:

var dataArray = $.makeArray($("input[type=radio]").serializeArray()); 

爲了讓自己的名字和值的數組。然後我把它轉換成JSON有:

var json = $.toJSON(dataArray) 

,然後用jQuery的阿賈克斯()的MVC控制器

$.ajax({ 
url: "/Rounding.aspx/Round/" + $("#OfferId").val(), 
type: 'POST', 
dataType: 'html', 
data: json, 
contentType: 'application/json; charset=utf-8', 
beforeSend: doSubmitBeforeSend, 
complete: doSubmitComplete, 
success: doSubmitSuccess}); 

其中發送跨原生JSON數據數據發佈。

然後,您可以捕獲響應流並將其反序列化爲本機C#/ VB.net對象,並在您的控制器中對其進行處理。

要在一個可愛的,低維護的方式自動完成這一過程,我建議閱讀本條目闡述了最原始,自動JSON反序列化的非常好。

匹配您的JSON對象以匹配您的模型,下面的鏈接過程應自動將數據反序列化到您的控制器中。這對我來說太棒了。

Article on MVC JSON deserialization

+0

順便說一句,我使用的JSON庫是:http://code.google.com/p/jquery-json/ – Evildonald

+0

提供的鏈接已死亡。 – JoshYates1980

25

如果您需要將完整的模型發送到控制器,首先需要的模式提供給您的JavaScript代碼。

在我們的應用程序,我們這樣做有一個擴展方法:

public static class JsonExtensions 
{ 
    public static string ToJson(this Object obj) 
    { 
     return new JavaScriptSerializer().Serialize(obj); 
    } 
} 

在視圖,我們用它來渲染模型:

<script type="javascript"> 
    var model = <%= Model.ToJson() %> 
</script> 

然後,您可以通過模型變量成你的$ .ajax調用。

+2

這很好,但是沒用,如果你改變模型在頁面上的模型被渲染,並且如果你在頁面上修改它(我認爲在網頁上是正常的),你會將一個空模型傳遞給post action。 – theLaw

+1

@Laviak這種方法看起來不錯,但在這種情況下返回空模型:我使用填充模型提交表單,並在表單從控制器返回時發生錯誤。在這種情況下,模型不是空的,但是當使用這個方法時,一個空模型被髮送給控制器。如何解決它? –

+0

@theLaw解決這個問題的任何想法? –

49

簡單的答案(在MVC 3以上,甚至可能是2)你不必做任何特殊的事情。

只要你的JSON參數匹配模型,MVC足夠聰明,可以根據你提供的參數構造一個新的對象。不在那裏的參數只是默認的。

例如,使用Javascript:

var values = 
{ 
    "Name": "Chris", 
    "Color": "Green" 
} 

$.post("@Url.Action("Update")",values,function(data) 
{ 
    // do stuff; 
}); 

型號:

public class UserModel 
{ 
    public string Name { get;set; } 
    public string Color { get;set; } 
    public IEnumerable<string> Contacts { get;set; } 
} 

控制器:

public ActionResult Update(UserModel model) 
{ 
    // do something with the model 

    return Json(new { success = true }); 
} 
+0

的答案是否可以與情景一起使用,其中模型包含部分視圖的自定義對象?像內部值數組中有屬性''Customer':{「Name」:「N」,...}「' – Javidan

+0

你將如何引用聯繫人,如Contact.Name,Contact.Phone等在ajax成功內? – JoshYates1980

1

您可以創建一個變量,發送給阿賈克斯。

var m = { "Value": @Model.Value } 

$.ajax({ 
    url: '<%=Url.Action("ModelPage")%>', 
    type: "POST", 
    data: m, 
    success: function(result) { 
     $("div#updatePane").html(result); 
    }, 

    complete: function() { 
    $('form').onsubmit({ preventDefault: function() { } }); 

    } 
}); 

所有模型的字段都必須以m爲單位。

0

在AJAX調用mention-

data:MakeModel(), 

使用以下函數來將數據綁定到模型

function MakeModel() { 

    var MyModel = {}; 

    MyModel.value = $('#input element id').val() or your value; 

    return JSON.stringify(MyModel); 
} 

附加[HttpPost]屬性到控制器動作

上POST此數據將可用

3

這可以通過構建一個JavaScript對象來匹配你的mvc模型。 JavaScript屬性的名稱必須與mvc模型完全匹配,否則自動綁定不會發生在帖子上。一旦在服務器端建立了模型,您就可以操作它並將數據存儲到數據庫中。

我正在通過網格行上的雙擊事件或點擊某種按鈕上的事件來實現此目的。

@model TestProject.Models.TestModel 

<script> 

function testButton_Click(){ 
    var javaModel ={ 
    ModelId: '@Model.TestId', 
    CreatedDate: '@Model.CreatedDate.ToShortDateString()', 
    TestDescription: '@Model.TestDescription', 
    //Here I am using a Kendo editor and I want to bind the text value to my javascript 
    //object. This may be different for you depending on what controls you use. 
    TestStatus: ($('#StatusTextBox'))[0].value, 
    TestType: '@Model.TestType' 
    } 

    //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
    //By parsing the Type to an int this worked. 

    javaModel.TestType = parseInt(javaModel.TestType); 

    $.ajax({ 
     //This is where you want to post to. 
     url:'@Url.Action("TestModelUpdate","TestController")', 
     async:true, 
     type:"POST", 
     contentType: 'application/json', 
     dataType:"json", 
     data: JSON.stringify(javaModel) 
    }); 
} 
</script> 


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post. 

[HttpPost] 
public ActionResult TestModelUpdate(TestModel newTestModel) 
{ 
TestModel.UpdateTestModel(newTestModel); 
return //do some return action; 
}