【问题标题】:Is there any way to force a model to be revalidated in an MVC3 controller?有什么方法可以强制在 MVC3 控制器中重新验证模型?
【发布时间】:2011-11-10 15:52:34
【问题描述】:

我有一个模型,其中包含两次地址和人员,一次用于“主要”联系人,一次用于“发票”联系人,以及一个名为 InvoiceContactSameAsMain 的布尔值 - 一个笨拙的名称,但具有描述性。该属性的 getter 检查“main”和“invoice”的 Address 和 Contact 对象是否相同,如果相同则返回 true。 setter 检查该值是否为真,如果是,则将主要 Person 复制到发票 Person 上,并将主要 Address 复制到发票地址上。

在我看来,布尔值由复选框表示(如您所料)。附带一个小的 JS 函数,如果选中该复选框,它会隐藏发票字段并通过将 data-val HTML 属性设置为 false 并强制重新解析不显眼的内容来“关闭”客户端验证表单中的验证属性。取消选中该框自然会显示字段并重新打开验证。

这一切都很好,直到我到达我的控制器。

尽管模型是“有效的”并且包含正确的字段(感谢我的 InvoiceContactSameAsMain 设置器),但 ModelState.IsValid 仍然是绝对错误的,而且我似乎找不到任何方法来重新验证模型。如果我清除 ModelState,所有错误都会消失。我宁愿避免按名称挖掘 ModelState 中的字段,因为 Person 和 Address 对象在整个项目中使用,并且可能需要在某些时候进行更改或扩展。

我在这里遗漏了什么明显的东西可以让我重新验证 ModelState?我尝试过 TryUpdateModel 和 TryValidateModel,但它们似乎都使用缓存的 ModelState 值。我什至尝试再次递归调用我的 Action,传入“固定”模型。我几乎很庆幸没有工作。

如果有更多细节或示例有帮助,请告诉我。

编辑:显然,如果这是解决问题的完全错误的方法,请告诉我。

编辑 2:根据 Ron Sijm 的建议添加了代码示例。

型号如下: 公开课详情 { 公共诠释?用户 ID { 获取;放; }

    public Company Company { get; set; }

    public Address CompanyAddress { get; set; }
    public Person MainPerson { get; set; }

    public Address InvoiceAddress { get; set; }
    public Person InvoiceContact { get; set; }

    [Display(Name = "Promotional code")]
    [StringLength(20, ErrorMessage = "Promotional code should not exceed 20 characters")]
    public string PromotionalCode { get; set; }

    [Display(Name = "Invoice contact same as main")]
    public bool InvoiceContactSameasMain
    {
        get { return InvoiceContact.Equals(MainPerson); }
        set
        {
            if (value)
            {
                InvoiceContact = MainPerson.Copy();
                InvoiceAddress = CompanyAddress.Copy();
            }
        }
    }

    [_Common.MustAccept]
    [Display(Name = "I agree with the Privacy Policy")]
    public bool PrivacyFlag { get; set; }

    [Display(Name = "Please subscribe to Sodexo News Letter")]
    public bool MarketingOption { get; set; }

    [Display(Name = "Contract number")]
    public int? ContractNumber { get; set; }

    public Details()
    {
        Company = new Company();
        CompanyAddress = new Address();
        MainPerson = new Person();
        InvoiceAddress = new Address();
        InvoiceContact = new Person();
    }
}

这是包装在 ViewModel 中的,因为页面中涉及许多 SelectList:

public class DetailsViewModel
{
    public Details    Details              { get; set; }
    public SelectList MainContactTitles    { get; set; }
    public SelectList InvoiceContactTitles { get; set; }
    public SelectList SICCodes             { get; set; }
    public SelectList TypesOfBusiness      { get; set; }
    public SelectList NumbersOfEmployees    { get; set; }

    public DetailsViewModel()
    {
    }
}

Controller的两个相关动作如下:

public class DetailsController : _ClientController
{
    [Authorize]
    public ActionResult Index()
    {
        DetailsViewModel viewModel = new DetailsViewModel();
        if (Client == null)
        {
            viewModel.Details = DetailsFunctions.GetClient((int)UserId, null);
        }
        else
        {
             viewModel.Details = DetailsFunctions.GetClient((int)UserId, Client.ContractNumber);
        }
        viewModel.MainContactTitles = DetailsFunctions.GetTitles((int)UserId, viewModel.Details.MainPerson.title);
        viewModel.InvoiceContactTitles = DetailsFunctions.GetTitles((int)UserId, viewModel.Details.InvoiceContact.title);
        viewModel.SICCodes = DetailsFunctions.GetSICCodes(viewModel.Details.Company.sic_code);
        viewModel.NumbersOfEmployees = DetailsFunctions.GetNumbersOfEmployees(viewModel.Details.Company.number_of_employees);
        viewModel.TypesOfBusiness = DetailsFunctions.GetTypesOfBusiness(viewModel.Details.Company.public_private);
        return View(viewModel);
    }

    [Authorize]
    [HttpPost]
    public ActionResult Index(DetailsViewModel ViewModel)
    {
        if (ModelState.IsValid)
        {
            //go to main page for now
            DetailsFunctions.SetClient((int)UserId, ViewModel.Details);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ViewModel.MainContactTitles = DetailsFunctions.GetTitles((int)UserId, ViewModel.Details.MainPerson.title);
            ViewModel.InvoiceContactTitles = DetailsFunctions.GetTitles((int)UserId, ViewModel.Details.InvoiceContact.title);
            ViewModel.SICCodes = DetailsFunctions.GetSICCodes(ViewModel.Details.Company.sic_code);
            ViewModel.NumbersOfEmployees = DetailsFunctions.GetNumbersOfEmployees(ViewModel.Details.Company.number_of_employees);
            ViewModel.TypesOfBusiness = DetailsFunctions.GetTypesOfBusiness(ViewModel.Details.Company.public_private);
            return View(ViewModel);
        }
    }
}

如果需要,我可以提供视图和 JS,但由于模型绑定一切正常,我不确定这有多大帮助。

【问题讨论】:

  • 我认为您所拥有的代码示例会有所帮助
  • 你可以看到为什么在调试的时候ModelState.IsValid是假的。如果您展开一些节点,您将看到哪些规则失败了。
  • @Darcy:失败的规则是复制的发票地址和人员中的规则。验证器仍然将它们视为空白,即使我可以看到它们在模型中正确填写。
  • 我刚刚尝试将我的“发票联系人与主要联系人相同”逻辑颠倒过来:它现在是一个简单的布尔值,发票联系人和发票地址的 getter 会检查它并返回主要联系人(或地址)如果布尔值为真。这对问题没有任何影响,并且 ModelState 仍然认为这些字段是空的,即使 Model 将它们清楚地显示为已填充。

标签: asp.net-mvc-3 validation controller


【解决方案1】:

这是一个中等程度的废话,但我最终只是在检查 ModelState.IsValid 之前清除了控制器中相关字段的 ModelState 错误:

if(ViewModel.Details.InvoiceContactSameasMain)
        {
            //iterate all ModelState values, grabbing the keys we want to clear errors from
            foreach (string Key in ModelState.Keys)
            {
                if (Key.StartsWith("Details.InvoiceContact") || Key.Startwith("Details.InvoiceAddress"))
                {
                    ModelState[Key].Errors.Clear();
                }
            }
        }

唯一的好处是,如果 Person 或 Address 对象发生更改,则无需更改此代码。

【讨论】:

  • +1 这是我为一个非常相似的问题找到的唯一类似于有效解决方案的东西。似乎应该有更好的方法,但我不知道它是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-20
  • 2015-01-28
  • 1970-01-01
  • 2013-01-05
相关资源
最近更新 更多