I am trying to have an 'Add New' link which opens a modal window containing an AJAX form, which posts to the server and updates my table with the new data.
From another question I have managed to get my form (which is contained in a partial view) to open in a jQuery dialogue and submit successfully. However if the model is not valid, I can not figure how out how to show the validation errors back to the user.
My controller:
public ActionResult AddItemOptionForm()
{
return PartialView("_AddItemOption");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateItemOption(ItemDetailItemOptionViewModel model)
{
model.ItemId = 1;
if (ModelState.IsValid)
{
//.....
//Code here to save to the DB - this bit works as expected
//.....
return PartialView("_ItemOptionList", itemdetailviewmodel);
}
return View(model);
}
_AddItemOption partial view:
@model shopServer1.Models.ViewModels.ItemDetailItemOptionViewModel
@using (Ajax.BeginForm("CreateItemOption", "Item",
new AjaxOptions
{
InsertionMode=InsertionMode.Replace,
UpdateTargetId="item-options-list",
HttpMethod="POST",
OnFailure = "handleError",
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.ItemOptionId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ItemOptionId)
@Html.ValidationMessageFor(model => model.ItemOptionId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ItemOptionCode)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ItemOptionCode)
@Html.ValidationMessageFor(model => model.ItemOptionCode)
</div>
//....
<input type="submit" value="Create" />
</fieldset>
}
And finally the javascript I use to show the dialogue:
<script type="text/javascript">
$(document).ready(function () {
$('#addItemOption').click(function () {
var url = $('#itemOptionModal').data('url');
$.get(url, function (data) {
$('#itemOptionFormContainer').html(data);
$('#itemOptionModal').modal('show');
});
});
});
I guess my question is two fold. Firstly am I approaching this in the correct manner? It seems a little overcomplicated to just display a partial view in a popup and handle the form post. And if this is a good approach how do I go about handling the validation? I've tried passing the itemdetailviewmodel
back to the partial view but that doesn't seem to do the trick.