Я сделал ниже, и у меня это работало в MVC 3.
В моем сценарии у меня было 3 формы (3 частичных просмотра) на странице, и я просто хотел, чтобы они отправляли через ajax и обновляли соответствующий частичный просмотр.
После обновления формы нужно динамически добавить обратно обработчик события submit и также вызвать $ .validator.unobtrusive.parse ('# Form1); заставить проверку на стороне клиента работать для следующих представлений.
Используемая ниже функция для получения частичного представления html в строке в методе Action контроллера.
//Renders Partial View as a string
//Parameters: Calling Controller Context, partial view name, model
//Reference:/2897925/render-view-programmno-v-stroku
public static string RenderPartialViewToString(ControllerContext context, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
context.Controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
ViewContext viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
// copy model state items to the html helper
foreach (var item in viewContext.Controller.ViewData.ModelState)
if (!viewContext.ViewData.ModelState.Keys.Contains(item.Key))
{
viewContext.ViewData.ModelState.Add(item);
}
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
1. Индекс просмотра -
<script type='text/javascript'>
$(document).ready(function () {
//Add Event handlers for the forms after document is ready.
$("#Form1").submit(Form1SubmitHandler);
$("#Form2").submit(Form2SubmitHandler);
$("#Form3").submit(Form3SubmitHandler);
});
//Submit Event handler for Form1Form
function Form1SubmitHandler(event) {
event.preventDefault();
if ($("#Form1").valid()) {
Form1Ajax();
}
}
//Submit Event handler for Form2 Form
function Form2SubmitHandler(event) {
event.preventDefault();
if ($("#Form2").valid()) {
Form2Ajax();
}
}
//Submit Event handler for Form3 Form
function Form3SubmitHandler(event) {
event.preventDefault();
if ($("#Form3").valid()) {
Form3Ajax();
}
}
//Submit Form1
function Form1Ajax() {
if ($("#Form1").valid())
{
$.ajax({
type: 'POST',
url: '@Url.Action("Action1", "Controller")',
cache: false,
data: { //send your form values here
},
dataType: "json",
success: function (data) {
if (data.IsSuccess) {
//Update the partial view.
$("#Form1Partial").html(data.ViewHtml);
//Have to call this to make client side validation work after dynamically adding a form.
$.validator.unobtrusive.parse('#Form1');
//Add event handler for submit.
$("#Form1").bind("submit", Form1SubmitHandler);
}
else {
//Update the partial view.
$("#Form1Partial").html(data.ViewHtml);
//Have to call this to make client side validation work after dynamically adding a form.
$.validator.unobtrusive.parse('#Form1);
//Add event handler for submit.
$("#Form1").bind("submit", Form1SubmitHandler);
}
}
});
}
}
//Submit Form2
function Form2Ajax() {
if ($("#Form2").valid())
{
$.ajax({
type: 'POST',
url: '@Url.Action("Action2", "Controller")',
cache: false,
data: { //send your form values here
},
dataType: "json",
success: function (data) {
if (data.IsSuccess) {
//Update the partial view.
$("#Form2Partial").html(data.ViewHtml);
//Have to call this to make client side validation work after dynamically adding a form.
$.validator.unobtrusive.parse('#Form2');
//Add event handler for submit.
$("#Form2").bind("submit", Form2SubmitHandler);
}
else {
//Update the partial view.
$("#Form2Partial").html(data.ViewHtml);
//Have to call this to make client side validation work after dynamically adding a form.
$.validator.unobtrusive.parse('#Form2);
//Add event handler for submit.
$("#Form2").bind("submit", Form2SubmitHandler);
}
}
});
}
}
//Submit Form3
function Form3Ajax() {
if ($("#Form3").valid())
{
$.ajax({
type: 'POST',
url: '@Url.Action("Action3", "Controller")',
cache: false,
data: { //send your form values here
},
dataType: "json",
success: function (data) {
if (data.IsSuccess) {
//Update the partial view.
$("#Form3Partial").html(data.ViewHtml);
//Have to call this to make client side validation work after dynamically adding a form.
$.validator.unobtrusive.parse('#Form3);
//Add event handler for submit.
$("#Form3").bind("submit", Form3SubmitHandler);
}
else {
//Update the partial view.
$("#Form3Partial").html(data.ViewHtml);
//Have to call this to make client side validation work after dynamically adding a form.
$.validator.unobtrusive.parse('#Form3);
//Add event handler for submit.
$("#Form3").bind("submit", Form3SubmitHandler);
}
}
});
}
}
<div id="Form1Partial">@Html.Partial("Form1Partial", Model.model1)</div>
<div id="Form2Partial">@Html.Partial("Form2Partial", Model.model2)</div>
<div id="Form3Partial">@Html.Partial("Form3Partial", Model.model3)</div>
2. Form1PartialView
@using (Html.BeginForm("Action1", "Controller", FormMethod.Post, new { @id = "Form1" }))
{
<!-Form elements go here->
<button type='submit'>Submit Form1</button>
}
3. Form2PartialView
@using (Html.BeginForm("Action2", "Controller", FormMethod.Post, new { @id = "Form2" }))
{
<!-Form elements go here->
<button type='submit'>Submit Form2</button>
}
4. Form3PartialView
@using (Html.BeginForm("Action3", "Controller", FormMethod.Post, new { @id = "Form3" }))
{
<!-Form elements go here->
<button type='submit'>Submit Form3</button>
}
5. Код контроллера
[HttpPost]
public ActionResult Action1(Model model)
{
if (ModelState.IsValid)
{
//Do some thing
return Json ( new { IsSuccess = true, ViewHtml = RenderPartialViewToString(ControllerContext, "Form1Partial", model) });
}
// If we got this far, something failed,
return Json ( new { IsSuccess = false, ViewHtml = RenderPartialViewToString(ControllerContext, "Form1Partial", model) });
}
[HttpPost]
public ActionResult Action2(Model model)
{
if (ModelState.IsValid)
{
//Do some thing
return Json ( new { IsSuccess = true, ViewHtml = RenderPartialViewToString(ControllerContext, "Form2Partial", model) });
}
// If we got this far, something failed,
return Json ( new { IsSuccess = false, ViewHtml = RenderPartialViewToString(ControllerContext, "Form2Partial", model) });
}
[HttpPost]
public ActionResult Action3(Model model)
{
if (ModelState.IsValid)
{
//Do some thing
return Json ( new { IsSuccess = true, ViewHtml = RenderPartialViewToString(ControllerContext, "Form3Partial", model) });
}
// If we got this far, something failed,
return Json ( new { IsSuccess = false, ViewHtml = RenderPartialViewToString(ControllerContext, "Form3Partial", model) });
}