如何在一个表单中使用ViewModels接收表单post和验证

本文关键字:表单 ViewModels post 验证 一个 | 更新日期: 2023-09-27 18:03:51

模型A具有两个属性,模型B具有强类型的IEnumerable模型类

期望实现以下目标:接收表单数据->验证两个模型->传输集合。

技术困难:

Form data: 
Model A: 
property one, property two data [Pass] 
Model B:  
Rec#1: Title, Firstname, Lastname [Available in the collection] 
Rec#2: Title, Firstname, lastname [Not available in the collection]

我使用模型B向控制器提交两行数据(见图片)。集合只包含第一行数据。模型b是强类型类,无法验证集合,或者不知道如何收集数据并进行验证。如何做到这一点?

建模
public class TestOneModel
{
    [Required]
    public string PropertyOne { get; set; }
    [Required]
    public string PropertyTwo { get; set; }
}
模型B

public class PassengerModel
{
    public string Title { get; set; }
    [Required(ErrorMessage = "Please enter first name")]
    [StringLength(20, ErrorMessage = "First Name not be exceed 20 char")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Please enter last name")]
    [StringLength(20, ErrorMessage = "LastName not be exceed 20 char")]
    public string LastName { get; set; }
}

视图模型
public class IndexViewModel
{
    public TestOneModel TestOne { get; set; }
    public PassengerModel NewPassenger { get; set; }
    public List<PassengerModel> Passengers { get; set; }
}
视图

@model MultipleModelsDemo.ViewModels.IndexViewModel
@using MultipleModelsDemo.ViewModels.vmConstants
@using MultipleModelsDemo.Helpers
@{
    Html.Raw(TempData["passengerOrdering"]);
}
<div>
    @using (Html.BeginForm("MyEditActionOne", "Checkout"))
    {       
        <div>
            <h4>Send Model One</h4>
            <fieldset>
                @Html.ValidationSummary(true, "ValidationSummary")
                <ol>
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyOne)
                        @Html.TextBoxFor(m => m.TestOne.PropertyOne)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyOne)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyTwo)
                        @Html.TextBoxFor(m => m.TestOne.PropertyTwo)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyTwo)
                    </li>
                </ol>
            </fieldset>
            <div style="margin:3%;">
                @*@Html.Partial("~/Views/Checkout/Index.cshtml", Model.Passengers)*@
                @foreach (var item in Model.Passengers)
                {
                    //Html.RenderPartial("EditorRow", item);
                    <div class="editorRow">
                        //@using (Html.BeginCollectionItem("PassengerModel")) 
                        //{
                            @Html.Raw(TempData["passengerOrdering"])  
                            <li>
                                @Html.LabelFor(m => m.NewPassenger.Title, "Title")
                                @Html.DropDownListFor(m => m.NewPassenger.Title, vmConstants.EnqTypes)
                            </li>
                            <li>
                                @Html.LabelFor(m => m.NewPassenger.FirstName, "First Name")
                                @Html.TextBoxFor(m => m.NewPassenger.FirstName, new { size = "25" })
                                @Html.ValidationMessageFor(m => m.NewPassenger.FirstName)
                            </li>
                            <li>
                                @Html.LabelFor(m => m.NewPassenger.LastName, "Last Name")
                                @Html.TextBoxFor(m => m.NewPassenger.LastName, new { size = "25" })
                                @Html.ValidationMessageFor(m => m.NewPassenger.LastName)
                            </li>
                          //}
                     </div>                
                }
            </div>
            <input class="btn" type="submit" value="Send" />
        </div>
    }
</div>
控制器

[HttpPost]
public ActionResult MyEditActionOne(IndexViewModel model)
{           
    if (ModelState.IsValid)
    {
        return View("Index", model);
    }
    model.Passengers = _repository.GetPassengers();
    return View("Index", model);
}

如何在一个表单中使用ViewModels接收表单post和验证

您确定包含了这些脚本吗?

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js"));

并添加:

  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
  <appSettings>

对于validate,您可以捕获如下错误:

 ModelState.AddModelError("keyName","Message");

显示它:

 @Html.ValidationMessage("keyName")