ASP.NET MVC 2: How to master common update/create scenarios with popups using jQuery
I have an Index page. In the contentwrap div the overlay is rendered and popuped by jQuery. The gridcontainer shall be updated via ajax.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
List of Employees</h2>
<br />
<div id="gridcontainer">
<% Html.RenderPartial("Grid", Model); %>
</div>
<%= Html.StandardOverlayCreateButton() %>
<div class="apple_overlay" id="overlay">
<div class="contentWrap">
</div>
</div>
</asp:Content>
I have the partial view Grid:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<UserInterface.Models.EmployeeForm>>" %>
<div>
<table>
...
</table>
</div>
And I have the Create page/overlay that is rendered into the contentWrap div:
<div>
<h2>
Create</h2>
<% using (Ajax.BeginForm("Create", "Employee", new AjaxOptions { HttpMethod = "POST", OnComplete = "$(\"a[rel]\").close()", InsertionMode = InsertionMode.Replace, UpdateTargetId = "gridcontainer" }))
{
%>
<% Html.E开发者_StackOverflow中文版nableClientValidation(); %>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
...
</fieldset>
<p>
<input type="submit" value="Create" />
</p>
<% } %>
</div>
EmployeeController:
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(Employee employee, [Optional, DefaultParameterValue(0)] int teamId)
{
employee.AddTeam(_teamRepository.GetById(teamId));
_employeeRepository.SaveOrUpdate(employee);
var updatedmodel = Mapper<List<Employee>, List<EmployeeForm>>(_employeeRepository.GetAllEmployeesWithEagerLoadedTeams());
// What do I have to return here?!
return View(updatedmodel);
}
How can I update the partial view Grid after I created the new employee without loading the whole Index page?
Thanks in advance!
You can use jQuery to post to the controller:
$.ajax({
type: 'POST',
url: '<%=Url.Action("Create", Customer")%>',
data: {
CustomerName: $('#CustomerName').val(),
CustomerAddress: $('#CustomerAddress').val()
},
dataType: 'json',
complete: function(XMLHttpRequest, textStatus) {
var Response = $.parseJSON(XMLHttpRequest.responseText);
// Add element to the grid
if (Response.Id > 100) {
var Li = $('#myGridRow');
var rowEl = $("<div></div>").text(Response.CustomerCode)
.appendTo(Li);
}
}
});
The controller would read the parameters:
[HttpPost]
public ActionResult Create(string CustomerName, string CustomerAddress)
{
// Save
var Result = new ReturnObject();
Result.Id = 100; // DB Id
Result.CustomerName = CustomerName;
return (Json(Result));
}
ReturnObject would be an object you want to send back to the jQuery call in a JSON format. I can't paste the whole code. I've tried to simplify trying to focus on the main aspects.
精彩评论