简体   繁体   English

MVC 4部分模型验证

[英]MVC 4 Partial Model Validation

I have a standard EF model with data annotations. 我有一个带有数据注释的标准EF模型。 I have two columns. 我有两列。 The first is an ID while the other is a boolean. 第一个是ID,另一个是布尔值。 In the database both are non nullable. 在数据库中,两者都是不可为空的。 They are both flagged however with the "Hidden" attribute. 但是,它们都带有“隐藏”(Hidden)属性标记。 This all works great for the UI until I go to post the form back to the server. 在我将表单发回到服务器之前,这一切对于UI都非常有用。

The model fails to validate. 模型无法验证。 I tried Steven Sanderson's suggestion to create an action filter however it failes to remove the values I do not return to the server for validation. 我尝试了史蒂文·桑德森(Steven Sanderson)的建议来创建一个动作过滤器,但是它无法删除我没有返回到服务器进行验证的值。 I ended up reverting to the following which I think is quite ugly: 我最终回到了我认为很难看的以下内容:

try
{
    ModelState["LocationId"].Errors.Clear(); -- Really ugly!
    ModelState["IsEnabled"].Errors.Clear(); -- Seems really trashy to do it this way
    if (ModelState.IsValid)
    {
        location.IsEnabled = true; -- This will eventually move to my model definition
        _repo.InsertOrUpdate(location);
        _repo.Save();

        return RedirectToAction("Index");
    }
    return View();
}
catch (DataException ex)
{
    ModelState.AddModelError("dataError", ex);
    return View();
}

Does anyone have any other suggestions or ideas on how to clean this up or create a better solution? 是否有人对如何清理或创建更好的解决方案有其他建议或想法?

Thanks 谢谢

You could use a viewmodel and map the data you want to show/have the user input from your entity to your viewmodel. 您可以使用视图模型并将要显示的数据/从实体中获得的用户输入映射到视图模型。 On post you would then validate the input data on the viewmodel, map it back to the entity and save it to your database. 发布后,您将验证视图模型上的输入数据,将其映射回实体并将其保存到数据库。

Another way would be to remove the [Required] data annotations from your ID and boolean attributes, this way ModelState.IsValid should not return false 另一种方法是删除[Required]从您的ID和布尔属性数据的注释,这样ModelState.IsValid 不应返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM