简体   繁体   English

如何在asp.net mvc 3中验证多个模型?

[英]How to validate multiple models in asp.net mvc 3?

I have a simple model like: 我有一个简单的模型,如:

public class AppointmentModel
   {
      private static List<SampleModel> _list;

      public string ClientName {
         get;
         set;
      }

      [DataType( DataType.Date )]
      public DateTime Date {
         get;
         set;
      }

      public bool TermsAccepted {
         get;
         set;
      }

      public List<SampleModel> SampleModelList {
         get;
         set;
      }

      public static List<SampleModel> GetSampleList() {
         if ( _list == null ) {

            _list = new List<SampleModel>( 0 );

            _list.Add( new SampleModel {
               Id = 1,
               Name = "Test",
               IsChecked = false
            } );

            _list.Add( new SampleModel {
               Id = 2,
               Name = "Another test",
               IsChecked = true
            } );

            _list.Add( new SampleModel {
               Id = 3,
               Name = "All test",
               IsChecked = false
            } );
         }

         return _list;
      }
   }

SampleModel looks like (it is created to simulate checkbox inputs): SampleModel看起来像(它是为了模拟复选框输入而创建的):

public class SampleModel
   {
      public int Id {
         get;
         set;
      }

      public string Name {
         get;
         set;
      }

      public bool IsChecked {
         get;
         set;
      }
   }

In my view, I implemented: 在我看来,我实施了:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SimpleAppWithModelBinding.Models.AppointmentModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Page</h2>

   <% using ( Html.BeginForm(FormMethod.Post) ) { %>
         <%:Html.ValidationSummary()%>

      <p>Name: <%: Html.EditorFor( model => model.ClientName )%></p>
      <p>Date: <%: Html.EditorFor( model => model.Date )%></p>
      <p><%: Html.EditorFor( model => model.TermsAccepted )%> Accept terms</p>

      <%-- here I put the checkbox list using editor template --%>
      <%: Html.Action( "RenderPartialSample" ) %>

      <input type="submit" value="Test" />
   <%} %>

</asp:Content>

and the controller side, HomeController : 和控制器端, HomeController

      public ActionResult Page() {

         return View();
      }

      // explicit validate model
      [HttpPost]
      public ActionResult Page( AppointmentModel model ) {

        // do some verification here

         if ( model.SampleModelList == null || ( model.SampleModelList != null && model.SampleModelList.Count == 0 ) ) {
            ModelState.AddModelError( "SampleModelList", "Please check something !" );
         }

         if ( ModelState.IsValid ) {
            //do something here
            return View( "Completed", model );
         } else {
            return View( "Page", model );
         }
      }


      public PartialViewResult RenderPartialSample() {
         List<SampleModel> model = new List<SampleModel> {
            new SampleModel{
               Id = 1,
               IsChecked = true,
               Name = "Test"
            },

            new SampleModel{
               Id = 2,
               IsChecked = false,
               Name = "Test1"
            },

            new SampleModel{
               Id = 3,
               IsChecked = false,
               Name = "Test2"
            }
         };

         AppointmentModel a = new AppointmentModel();
         a.SampleModelList = model;

         return PartialView( "SamplePartialView", a.SampleModelList );
      }

The problem: 问题:

When I press submit, the public ActionResult Page( AppointmentModel model ) gave me a model and he has SampleModelList null, always is null. 当我按下提交时, public ActionResult Page( AppointmentModel model )给了我一个模型,他有SampleModelList null,总是为null。 I want to have the checked inputs in that list from model but maybe is not working because of partial view. 我希望从模型中获取该列表中的已检查输入,但由于部分视图可能无法正常工作。

How to validate two models in my case ? 如何在我的情况下验证两个模型? Or what is the best approach in my case, maybe my approach is not good. 或者在我的情况下最好的方法是什么,也许我的方法并不好。

Please help :) 请帮忙 :)

UPDATE: 更新:

SamplePartialView contains: SamplePartialView包含:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<SimpleAppWithModelBinding.Models.SampleModel>>" %>

<%: Html.EditorForModel() %>

and the template: 和模板:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SimpleAppWithModelBinding.Models.SampleModel>" %>

<%: Html.HiddenFor( x => x.Id ) %>
<%: Html.CheckBoxFor( x => x.IsChecked, new {
      value = Model.Id
   } )%>
<%: Html.LabelFor( x => x.IsChecked, Model.Name ) %>

<br />

You haven't shown the SamplePartialView partial but I suspect that inside you didn't respect the naming convention for your input fields. 您尚未显示SamplePartialView部分,但我怀疑您内部不尊重输入字段的命名约定。 They were not prefixed with SampleModelList in order to respect the naming convention of the default model binder. 它们没有使用SampleModelList作为前缀,以便遵守默认模型绑定器的naming convention

Inside this partial you should have input fields that look like this: 在这个局部内你应该有这样的输入字段:

<input type="text" name="SampleModelList[0].Id" value="1" />
<input type="text" name="SampleModelList[0].Name" value="name 1" />

<input type="text" name="SampleModelList[1].Id" value="1" />
<input type="text" name="SampleModelList[1].Name" value="name 1" />

...

Look at the rendered markup for your form and make sure you have respected this convention. 查看表单的呈现标记,并确保您已遵守此约定。

In order to respect this naming convention you could set the template prefix, either inside the child controller action rendering your partial: 为了遵守这个命名约定,您可以设置模板前缀,在子控制器操作内部呈现您的部分:

ViewData.TemplateInfo.HtmlFieldPrefix = "SampleModelList";
return PartialView("SamplePartialView", a.SampleModelList);

or inside the partial itself if you prefer: 或者如果您愿意,可以在部分内部:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<List<SimpleAppWithModelBinding.Models.SampleModel>>" 
%>
<% ViewData.TemplateInfo.HtmlFieldPrefix = "SampleModelList"; %>
<%= Html.EditorForModel() %>

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

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