代码之家  ›  专栏  ›  技术社区  ›  David Fox

如何在jQuery对话框中验证ViewModel?

  •  2
  • David Fox  · 技术社区  · 14 年前

    我的AddressEditViewModel有一堆标记为 [Required(ErrorMessage="My Error Message Here")] [DisplayName("etc")] . DisplayName属性工作:

    <%: Html.LabelFor(model => model.Field) %>
    

    ,我认为所需的属性也可以工作,但我不知道如何提供表单反馈(jqueryui对话框)。此表单通过$.ajax()提交,并以action方法提交:

    [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");
        }
    

    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返回true,即使 address.RequiredField 为空。 SubmitChanges()

    Html.ValidationMessageFor(...) 因为我不想打电话——只要边界)。

    closeEditForm Content("Ok") 无型号

    $('#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;
    });
    

    我提交的表格如下:

    $("#dialog-address-edit").dialog({
                ...lots of dialog settings
                buttons: {
                    'Save': function () {
                        $('#editform').submit();
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Omu    14 年前

    http://surveymaster.codeplex.com/ 我在这个项目中用jquery.form做了很多ajax,