In EditPhoto.cshtml:
@model vg_music.Models.images
@{
ViewBag.Title = "EditPhoto";
}
<h2>
EditPhoto2</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Ajax.BeginForm(new AjaxOptions{UpdateTargetId = "AjaxDiv"})) {
@Html.ValidationSummary(true)
<div id="AjaxDiv">
@Html.Partial("EditPhotoForm")
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
EditPhotoForm.cshtml:
@model vg_music.Models.images
<fieldset>
<legend>images</legend>
@Html.HiddenFor(model => model.id)
<div class="editor-label">
@Html.LabelFor(model => model.title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.title)
@Html.ValidationMessageFor(model => model.title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.comment)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.comment)
@Html.ValidationMessageFor(model => model.comment)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.filename)
</div>
<div class="editor-field">
<img src="@Url.Content("~/uploads/images/little/"+Model.filename)" alt="@Model.title"/><br />
</div>
<p>
<input type="submit" value="Сохранить" />
</p>
</fieldset>
PhotosController.cs: ....
[HttpPost]
public ActionResult EditPhoto(images obj)
{
if (ModelState.IsValid)
{
var db = new EditImagesModel();
db.SaveImage(obj);
if (Request.IsAjaxRequest()) //This does not work.
{
return PartialView("EditPhotoForm");
}
return RedirectToAction("EditPhotos");
}
return View();
}
....
Why is not satisfied:
if (Request.IsAjaxRequest())
{
return PartialView("EditPhotoForm");
}
Why is not satisfied:
Because you forgot to include:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your EditPhoto.cshtml
page. And because of this the Ajax.BeginForm
helper doesn't perform any AJAX request but a simple form POST.
Contrary to ASP.NET MVC 1.0 and 2.0 where Ajax.*
helpers such as Ajax.ActionLink
and Ajax.BeginForm
were polluting your markup with javascript obtrusively, in ASP.NET MVC 3 they simply generate HTML5 data-*
attributes on the corresponding DOM elements. This way markup and javascript is kept separate. And you need javascript to interpret those attributes. This javascript is located in the jquery.unobtrusive-ajax.js
script which needs to be included.