2013-03-20 69 views
0

我在MVC 4應用程序的同一頁面中使用了多個部分視圖和相同的強類型模型。 我想調用控制器中的單個動作並通過ajax調用返回模型並一次性將其用於所有部分視圖。如何在ajax中的多個部分視圖中使用相同的模型

+0

只是使它清楚,既然你「想調用一個單一的行動」,返回模型,那麼你的意思是行動(最有可能)返回一個JSON對象?而你是**不是**一次加載ajax中的部分視圖? – 2013-03-20 08:06:51

+0

是的,我正在返回一個json對象,並希望在單個事件中更新多個部分視圖 – serene 2013-03-20 08:16:10

+0

好吧,那麼你是**不** **在ajax中加載部分視圖 - 你沒有像'public PartialViewResult PartialView1() 。如果是這種情況,那麼您可以只針對每個部分視圖中的所需元素。你可以編輯你的文章,也可以包括你的兩個部分視圖,這樣我可以給你一個對你最有意義的答案嗎? – 2013-03-20 08:32:56

回答

1

你給的東西並不多,但讓我盡我所能,給出一個對你最有意義的例子。所以說,你有以下型號:

public class UserProfile 
{ 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
    /// <summary> 
    /// 
    /// </summary> 
    /// <remarks> 
    /// 1 = Premium Users 
    /// 2 = Basic Users 
    /// NOTE: I'm using int instead of an enum to make the sample more simple. 
    /// </remarks> 
    public int UserType { get; set; } 
} 

而且看起來像這樣的控制方法:

[HttpPost] 
    public ActionResult SomeAction(int id) 
    {    
     IEnumerable<UserProfile> profiles = some_method_that_does_something_and_builds_the_model(); 
     return Json(profiles); 
    } 

你可以做你的Ajax調用是這樣的:

$.post('@Url.Action("MyAction", "MyController")', { id: $('#myId').val() }, 
function (result) { 
       // you can use $.each here but for loop is more efficient         
       var list1 = ''; 
       var list2 = ''; 
       for (var i = 0; i < result.length; i++) { 
        // just add the name as p's for a simple example 
        // I build the result as string as it is more efficient than building p elements 
        if (result[i].UserType == 1) { 
         list1 += '<p>' + result[i].UserName + '</p>'; 
        } 
        else { 
         list2 += '<p>' + result[i].UserName + '</p>'; 
        } 
       } 
       $("#first").append(list1); 
       $("#second").append(list2); 
      }); 
+0

但是不是將結果值添加到字符串,我們可以調用已經定義的局部視圖來加載或渲染使用獲得的模型,如果否則段.. – serene 2013-03-20 09:55:40

+0

正如你所說,部分視圖已經被「渲染」了,所以你只需要更新其中的一些內容,我給你的是一個簡單的例子,讓你開始使用,我相信你有一個更復雜的視圖,你有多個html元素。 – 2013-03-20 10:03:28

+0

Have你曾經聽說過[Knockout.js](http://knockoutjs.com/)?我認爲這最能滿足你最後評論的需求,你可以[從這裏開始](http://learn.knockout js.com/)。 – 2013-03-20 10:04:56

相關問題