mvc4 AJAX更新同一页 [英] mvc4 ajax updating same page

查看:73
本文介绍了mvc4 AJAX更新同一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面上的用户列表,他们是一个Ajax事件时加载,当我点击选项卡(easytabs)上。然后我的ajax加载创建相同的选项卡新用户的局部视图。然后,我创建一个使用这种形式的一个新用户,但我不知道如何重新加载与用户的一个新的列表(包括新创建的用户)的第一个局部视图。

I have a list of users on a page, they are loaded during an ajax event when I click on a tab (easytabs). I then ajax load a create new user partial view to the same tab. I then create a new user using this form, but I do not know how to re-load the first partial view with a new list of users (including the newly created user).

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查看

    <%@ 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>

这个伟大的工程,我每次单击该选项卡时,数据被重新加载预期。

This works great, every time I click the tab, the data is re-loaded as expected.

现在,

在UsersPartial观点,我有一个加载另一个局部视图到这个局部视图另一个阿贾克斯ActionLink的,创建一个新用户:

In the UsersPartial view, I have another Ajax Actionlink that loads another partial view into this partial view, to create a new user:

HTML阿贾克斯的ActionLink从UsersPartial查看:

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

这加载以下的 CreateUserView视图的UsersPartial视图里面:

This loads the following CreateUserView view inside of the UsersPartial view:

    <%@ 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的code被称为控制器
CreateUserPartial控制器code:

[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");
    }

这所有的作品......在创建用户时,它说用户创建的!如预期。

This all works...when a user is created, it says User created! as expected.

现在对我的问题,我怎么重新装入新用户的UsersPartial视图中的列表?我不知道这部分了。我有一种感觉它与jQuery的ajax的成功方法去做,但我不知道如何重新加载用户列表,包括这个新创建的。

Now on to my question, how do I re-load the list within the UsersPartial view with the new user? I cannot figure this part out. I have a feeling it has to do with the jQuery ajax success method, but I do not know how to re-load the list of users, including this newly created one.

任何想法?

谢谢!

推荐答案

请不要回发的形式。而不是调用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视图,而不是内容类型

    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());
    }

这篇关于mvc4 AJAX更新同一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆