What is wrong if no validation errors are shown when the submitted data is null/empty? An error should be shown.
In the code block result.success == false, should I reload the view or tell jQuery to invalidate my model?
From my Post action in the controller I return the model errors so I have them on the client side.
What should I do now?
I am using MVC 3.0 with latest jQuery/UI 1.7.2/1.8.20:
<script type="text/javascript">
$(document).ready(function () {
// the div holds the html content
var $dialog = $('<div></div>')
.dialog({
autoOpen: false,
title: 'This is the dialogs title',
height: 400,
width: 400,
modal: true,
resizable: false,
hide: "fade",
show: "fade",
open: function (event, ui) {
$(this).load('@Url.Action("Create")');
},
buttons: {
"Save": function () {
var form = $('form', this);
$.ajax({
url: $(form).attr('action'),
type: 'POST',
data: form.serialize(),
dataType: 'json',
success: function (result) {
// debugger;
if (result.success) {
$dialog.dialog("close");
// Update UI
}
else {
// Reload the dialog to show model/validation errors
} // else end
} // success end
}); // Ajax post end
},
"Close": function () {
$(this).dialog("close");
}
} // no comma
});
$('#CreateTemplate').click(function () {
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
});
});
</script>
my form is:
@using (Html.BeginForm("JsonCreate", "Template"))
{
<p class="editor-label">@Html.LabelFor(model => model.Name)</p>
<p class="editor-field">@Html.EditorFor(model => model.Name)</p>
<p class="editor-field">@Html.ValidationMessageFor(model => model.Name)</p>
}
My controller is:
[HttpGet]
public ActionResult Create()
{
return PartialView();
}
[HttpPost]
public ActionResult JsonCreate(Template template)
{
if (ModelState.IsValid)
{
_templateDataProvider.AddTemplate(template);
// success == true should be asked on client side and then ???
return Json(new { success = true });
}
// return the same view with model when errors exist
return PartialView(template);
}
The working version is:
I changed this in my $.ajax request:
// dataType: 'json', do not define the dataType let the jQuery infer the type !
data: form.serialize(),
success: function (result)
{
debugger;
if (result.success) {
$dialog.dialog("close");
// Update UI with Json data
}
else {
// Reload the dialog with the form to show model/validation errors
$dialog.html(result);
}
} // success end
The Post action has to look like this:
[HttpPost]
public ActionResult JsonCreate(Template template)
{
if (!ModelState.IsValid) {
return PartialView("Create", template);
_templateDataProvider.AddTemplate(template);
return Json(new { success = true });
}
}
Either return the partialview which is the form (success == false) or return the JSON which is success == true.
Someone could still return a list of items to update the UI on client side:
return Json(new { success = true, items = list});