0

我在 MVC 4 应用程序的同一页面中使用具有相同强类型模型的多个部分视图。我想在控制器中调用单个操作并返回模型并通过 ajax 调用一次将其用于所有部分视图。

4

1 回答 1

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);
            });
于 2013-03-20T09:38:51.560 回答