如何创建Model类以验证表单字段

时间:2010-12-09 15:34:11

标签: asp.net-mvc

我是MVC的初学者。我创建了一个带有下拉列表,文本框和文本区域的视图。我没有创建强类型视图,因为这些字段不是从数据库生成的。这是正确的做法吗?我是否必须创建“模型”类并生成强类型视图?我想在保存到数据库之前验证(客户端和服务器端)这些fieds。如何为这些字段创建Model类?我很感激任何意见。

谢谢..

这是我的观点。

Create.aspx

<% using (Html.BeginForm()) { %>
   <div>
   <label for="Reason">Reason:</label>
    </div>
    <div>
    <%= Html.DropDownList("lstReasons", new SelectList((IEnumerable)ViewData["ReasonList"], "ReasonID", "ReasonDetail"), "Select Reason")%>
    </div>

     <div>
            <label for="StartDate">Start Date:</label>
    </div>
    <div>
            <%= Html.TextBox("StartDate")%>

    </div>

           <div>          
            <label for="Details">Details:</label>
           </div>
            <div>
            <%=Html.TextArea("Details")%> 
            </div>

    <input type="submit" value="Submit" />
    <input type="reset" value="Cancel" />
<% } %>

我的家庭控制器代码。

  public ActionResult Create()
    {
        var reasons = from reason in db.Reasons
                       select reason;

        ViewData["ReasonList"] = reasons;
    }

1 个答案:

答案 0 :(得分:2)

我想我明白你要做什么,这是我要做的一个例子:

创建一个视图模型,该模型使用数据注释来强制执行客户端验证(对于必填字段和字符串长度等):

public class CreateViewModel
{
    public SelectList Reasons { get; set; }  //to store list of reasons from db
    public string Reason { get; set; }  //to store selected reason

    [Required]
    public DateTime StartDate {get; set;}

    [Required]
    [StringLength(250, ErrorMessage = "Details must be less than 250 characters")]
    public string Details { get; set; }
}

为DetailsViewModel创建一个强类型的视图,并使用Html.EnableClientValidation打开客户端验证,并使用Html.ValidationMessageFor显示验证消息:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.CreateViewModel>" %>
<% Html.EnableClientValidation(); %>
<% Html.ValidationSummary(); %>

<% using (Html.BeginForm()) { %>
    <div>
        <label for="Reason">Reason:</label>
    </div>
    <div>
        <%= Html.DropDownListFor(m => m.Reason,Model.Reasons, "Select Reason")%>
    </div>

    <div>
        <label for="StartDate">Start Date:</label>
    </div>
    <div>
        <%= Html.TextBoxFor(m => m.StartDate)%>
        <%= Html.ValidationMessageFor(m => m.StartDate %>
    </div>

    <div>          
        <label for="Details">Details:</label>
    </div>
    <div>
        <%=Html.TextAreaFor(m => m.Details)%>
        <%= Html.ValidationMessageFor(m => m.Details %> 
    </div>

<input type="submit" value="Submit" />
<input type="reset" value="Cancel" />

&lt;%}%&gt;

在你的控制器方法Get方法中显示视图:

[HttpGet]
    public ActionResult Create()
    {
        var viewModel = new CreateViewModel();

        //get reasons from DB
        var reasons = from reason in db.Reasons
                      select reason;

        //set the reason Id as the unique identifier of the reason and the reason text to be what will be displayed in the dropdown
        var reasonItems = reasons.Select(r => new { ShortCode = reasons.Id, Definition = reasons.reasonText });

        //create a select list that will select the id as the value and show the definition in the label
        viewModel.Reasons = new SelectList(reasonItems, "ShortCode", "Definition");

        return View("", viewModel); //return the populated dropdown to the view
    }

并在您的控制器中Post方法检查使用ModelState.IsValid来检查视图数据是否是,如果没有添加模型状态错误,则显示在视图页面上:

[HttpPost]
    public ActionResult Create(CreateViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            // go and save your view model data 
        }
        ModelState.AddModelError("Error", "Values are not valid");

        return RedirectToAction("Create");
    }

在这种情况下,我只是添加一个模型状态错误,然后重定向到控制器Get方法,该方法将再次显示模型错误(即视图中的Html.ValidationSummary代码所示 - 显示模型状态错误自动地)。

我希望这会有所帮助。