我在MVC 4应用程序的同一页面中使用具有相同强类型模型的多个部分视图。 我想在控制器中调用单个动作并返回模型,并通过ajax调用立即将其用于所有部分视图。
答案 0 :(得分: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);
});