2017-03-13 69 views
1

我有ajax返回部分视图与强烈的类型 我希望成功获取模型的值。 有可能吗? 代码返回:mvc ajax返回部分视图与模型获取模型的值在成功

return View("Test", Model); 

在阿贾克斯: 我想要得到的数据varible模型

success: function (data) { 
     data. 
      } 
+0

取看看http://stackoverflow.com/questions/18050894/如何调用一个动作结果从jQuery和http://stackoverflow.com/questions/33201617/using-jquery-ajax-to-call-actionresult-method-in-controller-and-return-data as他们都解决你的问题。 – jonesy

回答

0

你的局部视图需要返回JSON数据,你能够访问这样的数据。

在你的控制器(我假设这是一个HTTPPost调用):

return Json(new { id = 1, name = "Test" }); 

在您的JS Ajax调用:

success: function(data) { 
    alert(data.name); //alerts 'Test' 
} 

更新 OK,如果你想拥有部分视图返回和模型,你可以返回视图,因为你已经然后将模型转换为JSON字符串来访问和使用JS中的视图也许吗?这里有一个粗略的例子...

在控制器

这样:

using System.Web.Script.Serialization; 
... 
var jsonstring = new JavaScriptSerializer().Serialize(Model); 
... 
ViewBag.JsonString = jsonString; 

然后在局部视图:

@{ 
    var jsonString = ViewBag.JsonString; 
} 
<script> 
var data = JSON.parse("@jsonString"); 
alert(data.name); //alerts 'Test' 
</script> 
+0

嗨,谢谢,但我需要返回部分视图和模型,在你的例子中,我如何在partirl视图中使用? – rikush

+0

@rikush更新 - 希望有所帮助。 – scgough

+0

你有'@ {0124}在你的部分视图的顶部(在'

0

没有,因为你需要从控制器动作返回JsonResult回这将如:

return Json(new {response = Model }); 

现在,它成功的ajax,你可以访问结果从这是返回的JSON对象:

success: function (data) { 
     console.log(data); 
      } 
0

试试这个是Ajax表单

OnSuccess = "ShowMessage()" 

和脚本是

<script> 
    function ShowMessage() { 
       document.getElementById('info').value='YOUR_MESSAGE'; 
       setTimeout(function() { 
       $("#info").hide(); 
       }, 3000); 
      } 
    <script> 

和你的HTML标签应该是这样的

<div id="info"></div>