【问题标题】:How can I validate specific field/property of specific model instance in ASP .NET MVC?如何验证 ASP .NET MVC 中特定模型实例的特定字段/属性?
【发布时间】:2012-12-27 12:52:12
【问题描述】:

我有一个具有 4 个属性的模型类:

public class ModelClass
    {
        [Required]
        public string Prop1 { get; set; }

        [MaxLength(5)]
        public string Prop2 { get; set; }

        [MinLength(5)]
        public string Prop3 { get; set; }

        [MinLength(5)]
        public string Prop4 { get; set; }
    }

查看,这里我只输入prop2:

@model ModelClass
@Html.TextBoxFor(m => m.Prop2)    

还有一些控制器:

[HttpPost]
        public ActionResult Index(ModelClass postedModel)
        {
            var originalModel = Session["model"] as ModelClass;
            return View();
        }

事情是:整个模型存储在Session,因为它填充在分离的视图上。我需要的是仅验证模型的Prop1,该模型存储在Session 中。如果验证失败,如果Prop1 无效,我需要重定向到其他View1 或View3,如果Prop3 无效等。在控制器中,我发布了只有Prop2 的模型和来自Session 的模型。我不能使用ModelState 和ModelState.IsValidField() 等方法,因为它将是发布模型的验证信息。我也不能使用controller.TryValidateModel(originalModel),因为我只得到false,我不会得到关于它为什么是false的信息,所以如果Prop1无效或我将无法重定向到View1如果Prop3 无效,则发送至View3。 那么我怎样才能只验证 originalModel 的 Prop1?

【问题讨论】:

    标签: c# asp.net asp.net-mvc model


    【解决方案1】:

    使用视图模型:

    public class Step1ViewModel
    {
        [Required]
        public string Prop1 { get; set; }
    }
    

    然后让你的视图强类型化到视图模型:

    @model Step1ViewModel
    @Html.TextBoxFor(m => m.Prop1) 
    

    最后让您的 HttpPost 控制器操作将视图模型作为操作参数,这样您就可以仅在当前向导步骤的上下文中成功验证它:

    [HttpPost]
    public ActionResult Index(Step1ViewModel postedModel)
    {
        if (!ModelState.IsValid)
        {
            // validation for this step failed => redisplay the view so that the 
            // user can fix his errors
            return View(postedModel);
        }
    
        // validation passed => fetch the model from the session and update the corresponding
        // property
        var originalModel = Session["model"] as ModelClass;
        originalModel.Prop1 = postedModel.Prop1;
    
        return RedirectToAction("Step2");
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 2020-01-21
      • 1970-01-01
      • 2020-06-15
      相关资源
      最近更新 更多