如何在Ajax响应中访问Model Data

时间:2016-06-29 08:57:31

标签: javascript jquery ajax asp.net-mvc pushstate

我有两种形式,考虑Form1和Form2,两者都只是MVC形式。这些表单使用两种不同的视图模型,如下所示:

public class Form1ViewModel
{
     //some public properties

     public string QueryString { get; set; }
}


public class Form2ViewModel
{
     //some public properties

     public string PreviousQueryString { get; set; }
}

在控制器Post Action中,我这样写:

[HttpPost]
public ActionResult ProcessForm1(Form1ViewModel form1Obj)
{
     //some logic goes here

     //I'm preparing Querystring from form1 data and appending to Form2 model like

     Form2ViewModel form2Obj=new Form2ViewModel();
     form2Obj.PreviousQueryString = form1Obj.QueryString;

     return View("Form2",form2Obj) ;
}

在Form1中,我通过Jquery Ajax提交

 frm.submit(function(ev) {
   var formData = frm.serialize();
   $.ajax({
     type: "POST",
     url: 'ControllerName/ProcessForm1',
     data: formData,
     success: function(response) {
       //Here i need to read the PreviousQueryString and need to push to window.history.pushState()
     }
     error: function() {}
   });
 });

在Ajax成功中,我需要从响应中读取PreviousQueryString。

我知道如何做客户端(使用纯JS),但这是我的要求。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

试试这个

[HttpPost]
public string ProcessForm1(Form1ViewModel form1Obj)
{
     JavaScriptSerializer js = new JavaScriptSerializer();
     Form2ViewModel form2Obj=new Form2ViewModel();
     form2Obj.PreviousQueryString = form1Obj.QueryString;
      return js.Serialize(form2Obj);
 }

success: function(response) {
          var objResponse = $.parseJSON(response);
        if (objResponse.PreviousQueryString != "") {
           alert(objResponse.PreviousQueryString);
        }
    }