My AddressEditViewModel has a bunch of attributes marked [Required(ErrorMessage="My Error Message Here")]
and/or [DisplayName("etc")]
. The DisplayName attributes work:
<%: Html.LabelFor(model => model.Field) %>
, and I think the Required attributes are working too, but I don't know how to provide feedback on the form (jQuery UI Dialog). This form is submitted via $.ajax(), and in the action method:
[HttpPost]
public ActionResult Edit(AddressEditViewModel address)
{
var addressToEdit = dc.Addresses.FirstOrDefault(x => x.AddressID == address.AddressIDEdit);
if (ModelState.IsValid)
{
//make sure there is at least one active address
if (!address.ActiveEdit && (addressToEdit != null && addressToEdit.Active))
{
if (dc.Addresses.Where(x => x.ProfileID == addressToEdit.ProfileID).Count(x => x.Active) == 1)
{
address.ActiveEdit = true;
}
}
try
{
//TryUpdateModel SUCKS!~
//use valueinjecter
addressToEdit.InjectFrom<VMToAddress>(address);
dc.SubmitChanges();
}
catch (Exception)
{
return View(address);
}
}
else
{
return View(address); //activate the red borders around textboxes
}
return Content("Ok");
}
And the little class for ValueInjecter:
public class VMToAddress : LoopValueInjection
{
protected override string TargetPropName(string sourcePropName)
{
if (sourcePropName.EndsWith("Edit"))
{
return sourcePropName.RemoveSuffix("Edit");
}
else if (sourcePropName.EndsWith("Create"))
{
return sourcePropName.RemoveSuffix("Create");
}
else
{
return sourcePropName;
}
}
}
ModelState.IsValid returns true even though address.RequiredField
is null. SubmitChanges()
throws a SqlException because it can't insert the NULL value. Am I not understanding how to use ModelState, or is there some other way to provide feedback on an invalid field? I'd like to set a red border around my textboxes like the model validation I've seen in a lot of the MVC tutorials, or maybe display my ErrorMessage value from the ViewModel.
Another Edit
Removed jQuery.validate and created a customer model binder to accommodate the commonly named elements. The custom model binder now even adds the validation messages (so I removed the Html.ValidationMessageFor(...)
calls since I don't want them--just the borders).
However, at Omu's suggestion to use the jQuery.form plugin, my model seems to be lost after the first postback. closeEditForm
just checks for a return of Content("Ok")
, closes the Edit dialog and finally refreshes the List dialog. But, after an error, it correctly does not close the dialog, gives me red borders (hooray), but on subsequent posts there is no model (boo) passed to my binder--just null values.
$('#editform').submit(function () {
$(this).ajaxSubmit({
target: '#editform', //this will allow validation classes to be added, etc
success: closeEditForm //this will close the edit form if the response text is "Ok"
});
return false;
});
I submit the form like this:
$("#dialog-address-edit").dialog({
...lots of dialog settings
buttons: {
'Save': function () {
$('#editform').submit();