簡體   English   中英

MVC4將所有表格數據(模型)從javascript傳遞到控制器-可能嗎?

[英]MVC4 passing all form data (model) from javascript to controller — is it possible?

的回覆

MVC3使用JavaScript將模型視圖傳遞給控制器

這意味着這是不可能的,至少對於MVC 3而言是不可能的。

我想知道MVC 4中是否有任何方法可以將整個表單內容(由模型表示)從.cshtml(剃刀)視圖快速傳遞到JavaScript中的控制器。

例如,如果我選擇一個下拉菜單,我可能想將表單中的所有字段返回給控制器,這將采取適當的措施。

顯然,對於大型表單,不希望必須逐個元素地進行此操作

基本上,您可以通過調用AJAX POST來做到這一點:

JS(使用jQuery):

$('form').on('submit', function (event) {
    // Stop the default submission
    event.preventDefault();

    // Serialize (JSON) the form's contents and post it to your action
    $.post('YourAction', $(this).serialize(), function (data) {
        // If you want to do something after the post
    });
});

控制器動作:

public ActionResult YourAction(string JSONmodel)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    MyModel model = serializer.Deserialize(JSONmodel, typeof(MyModel));

    // Now you can do whatever you want with your model
}

UPDATE

對於更復雜的對象,可以使用第三方解決方案進行序列化/反序列化。 有充分的文檔證明並廣泛使用:

Json.NET: http://json.codeplex.com/

是的,有可能以更簡單的方式。

  1. MelanciUK提供的示例的替代方案。

     $('form').on('submit', function (event) { // Stop the default submission event.preventDefault(); // User same property name as in Model $.post('YourAction', {prop1 : 'a', prop2 : 'b'}, function (data) { // If you want to do something after the post }); 

    });

     [HttpPost] public ActionResult SampleAction(SampleModel sModel) { } 

您可以通過標准MVC(ModelBinding)約定實現相同的功能,即無需序列化和反序列化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM