mvc4 ajax更新同一页面

时间:2012-09-18 19:37:15

标签: c# asp.net-mvc jquery

我在页面上有一个用户列表,当我点击一个标签(easytabs)时,它们会在ajax事件期间加载。然后我将ajax加载到同一个选项卡的创建新用户局部视图。然后我使用此表单创建一个新用户,但我不知道如何使用新的用户列表(包括新创建的用户)重新加载第一个局部视图。

HTML加载标签面板,其中包含用户列表:

<%= Ajax.ActionLink("Manage Users", "tabsUsers", null, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "ManageUsersPartial", InsertionMode = InsertionMode.Replace }, htmlAttributes: new { data_target = "#tabs-users" })%>

控制器:

[HttpGet]
public PartialViewResult tabsUsers()
{
    return PartialView("UsersPartial", userManager.GetUsers());
}

UsersPartial View

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<LMS.Data.User>>" %>

<p>
    <%: Ajax.ActionLink("Create New", "Create", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "CreateUserPartial", InsertionMode = InsertionMode.Replace })%>
</p>
<table>
    <tr>
        <th>
            <%: Html.DisplayNameFor(model => model.UserName) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.FirstName) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.LastName) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.Email) %>
        </th>
        <th>Actions</th>
    </tr>

<% foreach (var item in Model) { %>
    <tr>
        <td>
            <%: Html.DisplayFor(modelItem => item.UserName) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.FirstName) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.LastName) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.Email) %>
        </td>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { id = item.UserID })%> |
            <%: Html.ActionLink("Details", "Details", new { id=item.UserID }) %> |
            <%: Html.ActionLink("Delete", "Delete", new { id=item.UserID }) %>
        </td>
    </tr>
<% } %>

</table>

<br />

<div id="CreateUserPartial"></div>

这很好用,每次单击选项卡时,都会按预期重新加载数据。

现在,

在UsersPartial视图中,我有另一个Ajax Actionlink,它将另一个局部视图加载到这个局部视图中,以创建一个新用户:

来自UsersPartial View的

HTML Ajax Actionlink:

<%: Ajax.ActionLink("Create New", "Create", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "CreateUserPartial", InsertionMode = InsertionMode.Replace })%>

这会在UsersPartial视图中加载以下 CreateUserView视图

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<LMS.Data.User>" %>

<script src="<%: Url.Content("~/Scripts/jquery-1.6.2.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"></script>

<script type="text/javascript">
    $(function () {
        $('form').submit(function () {
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });
</script>

<div id="result"></div>

<% using (Html.BeginForm())
   { %>
<%: Html.ValidationSummary(true, "Could not create new user.") %>
<fieldset>
    <legend>User</legend>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.UserName) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.UserName) %>
        <%: Html.ValidationMessageFor(model => model.UserName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.FirstName) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.FirstName) %>
        <%: Html.ValidationMessageFor(model => model.FirstName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.LastName) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.LastName) %>
        <%: Html.ValidationMessageFor(model => model.LastName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.Password) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.Password) %>
        <%: Html.ValidationMessageFor(model => model.Password) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.Email) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.Email) %>
        <%: Html.ValidationMessageFor(model => model.Email) %>
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
<% } %>
<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>

最后,在控制器中调用CreateUser的代码 CreateUserPartial控制器代码:

[HttpPost]
    public ActionResult Create(AccountUser user)
    {
        if (ModelState.IsValid)
        {
            try
            {
                user.Password = user.Password.Encrypt();
                userManager.AddUser(user);
            }
            catch (DbEntityValidationException dbex)
            {
                foreach (var validationErrors in dbex.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            catch (DbUpdateException dbuex)
            {
                if (dbuex.InnerException != null)
                    if (dbuex.InnerException.InnerException != null)
                        if (dbuex.InnerException.InnerException.Message.Contains("Cannot insert duplicate key row in object"))
                            return Content("User already exists!", "text/html");
                else
                    ModelState.AddModelError("", "An unknown error occured when creating the user.");
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "An unknown error occured when creating the user.");
            }
        }

        return Content("User created!", "text/html");
    }

这一切都有效...当创建用户时,它表示用户创建了!正如所料。

现在回答我的问题,如何在新用户的UsersPartial视图中重新加载列表?我无法理解这一部分。我有一种感觉它与jQuery ajax成功方法有关,但我不知道如何重新加载用户列表,包括这个新创建的用户。

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

请不要回发表单。而不是调用ajax调用

  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<LMS.Data.User>" %>

<script src="<%: Url.Content("~/Scripts/jquery-1.6.2.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"></script>

<% using (Html.BeginForm())
 <%: Ajax.BeginForm("Create",new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "ManageUsersPartial", InsertionMode = InsertionMode.Replace }, htmlAttributes: new { data_target = "#tabs-users" })
   { %>
<%: Html.ValidationSummary(true, "Could not create new user.") %>
<fieldset>
    <legend>User</legend>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.UserName) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.UserName) %>
        <%: Html.ValidationMessageFor(model => model.UserName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.FirstName) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.FirstName) %>
        <%: Html.ValidationMessageFor(model => model.FirstName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.LastName) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.LastName) %>
        <%: Html.ValidationMessageFor(model => model.LastName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.Password) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.Password) %>
        <%: Html.ValidationMessageFor(model => model.Password) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.Email) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.Email) %>
        <%: Html.ValidationMessageFor(model => model.Email) %>
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
<% } %>
<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>

然后方法应返回paratail视图而不是Content Type

    public ActionResult Create(AccountUser user)
    {
        if (ModelState.IsValid)
        {
            try
            {
                user.Password = user.Password.Encrypt();
                userManager.AddUser(user);
            }
            catch (DbEntityValidationException dbex)
            {
                foreach (var validationErrors in dbex.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
return PartialView("CreateUserPartial", user);
            }
            catch (DbUpdateException dbuex)
            {
                if (dbuex.InnerException != null)
                    if (dbuex.InnerException.InnerException != null)
                        if (dbuex.InnerException.InnerException.Message.Contains("Cannot insert duplicate key row in object"))
                            return Content("User already exists!", "text/html");
                else
                    ModelState.AddModelError("", "An unknown error occured when creating the user.");
return PartialView("CreateUserPartial", user);
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "An unknown error occured when creating the user.");
return PartialView("CreateUserPartial", user);
            }

return PartialView("UsersPartial", userManager.GetUsers());
        }

        return PartialView("UsersPartial", userManager.GetUsers());
    }

答案 1 :(得分:0)

您必须在创建后返回新列表。而不是:

return Content("User created!", "text/html");

你应该这样做:

return PartialView("UsersPartial", userManager.GetUsers());

编辑:您的部分用户需要IEnumerable个用户。如果您需要留言,请通过ViewBag发送。