I'm trying to write Update function via ajax. These are my controller methods:
[ActionName("UpdatePhoto"), HttpPost]
public ActionResult UpdatePhotoPostViewModel(PhotoViewModel photo)
{
if (!ModelState.IsValid)
return PartialView("UpdatePhoto", photo);
TempData["Photo"] = photo;
return Json(new { success = true });
}
[ActionName("UpdatePhoto"), HttpGet]
public ActionResult UpdatePhotoGetViewModel(PhotoViewModel photo)
{
if (TempData["Photo"] != null)
photo = TempData["Photo"] as PhotoViewModel;
return PartialView(photo);
}
public ActionResult Photo(PhotoViewModel photo)
{
if (TempData["Photo"] != null)
photo = TempData["Photo"] as PhotoViewModel;
return PartialView("PhotoSummary", photo);
}
}
And View classes:
//PhotoSummary
@model PhotoAlbum.WEB.Models.PhotoViewModel
<div class="well">
<h3>
<strong>@Model.Name</strong>
<span class="pull-right label label-primary">@Model.AverageRaiting.ToString("# stars")</span>
</h3>
<span class="lead">@Model.Description</span>
@Html.DialogFormLink("Update", Url.Action("UpdatePhoto", new {photo = @Model}), "Update Photo", @Model.PhotoId.ToString(), Url.Action("Photo"))
</div>
//Main View
@model PhotoAlbum.WEB.Models.PhotoListViewModel
@{
ViewBag.Title = "My Photos";
}
@foreach (var p in @Model.Photos)
{
<div [email protected]()>
@Html.Action("Photo", new {photo = p})
</div>
}
Here my DialogFormLink helper:
public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
string dialogTitle, string updateTargetId, string updateUrl)
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(linkText);
builder.Attributes.Add("href", dialogContentUrl);
builder.Attributes.Add("data-dialog-title", dialogTitle);
builder.Attributes.Add("data-update-target-id", updateTargetId);
builder.Attributes.Add("data-update-url", updateUrl);
builder.AddCssClass("dialogLink");
return new MvcHtmlString(builder.ToString());
}
The problem is that object photo in UpdatePhotoGetViewModel method is null.
But I passed the model here:
@Html.DialogFormLink("Update", Url.Action("UpdatePhoto", **new {photo = @Model}**), "Update Photo", @Model.PhotoId.ToString(), Url.Action("Photo"))
Why this parameter wasn't injected?
DialogFormLink()? (its not part of MVC).DialogFormLinkclass.idproperty an getting the model again based on theid.new { Model }(notnew { photo = @Model }but not only will it generate an ugly query string, it will fail if the model contains any properties which are complex objects or collections, and your could exceed the query string limit and throw an exception.