How to create a Model class to Validate the form fields
I am beginner to MVC. I have created a View with dropdownlist, text box and text area. I didn't create a strongly typed view because these fields are not generating from the database. Is this right way of doing it? Do I have to create a 'Model' class and generate a strongly typed view? I am trying to validate(client and server side) these fieds before saving into the database. How to create a Model class for these fields? I appreciate any input.
Thank you..
Here is my view looks like.
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>
<di开发者_JS百科v>
<%=Html.TextArea("Details")%>
</div>
<input type="submit" value="Submit" />
<input type="reset" value="Cancel" />
<% } %>
My Home controller code.
public ActionResult Create()
{
var reasons = from reason in db.Reasons
select reason;
ViewData["ReasonList"] = reasons;
}
I think I understand what you are trying to do, here is an example of what I would do:
Create a view model which uses Data Annotations to enforce client side validation (for mandatory fields and string length etc.):
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; }
}
Have a view that is strongly typed to the DetailsViewModel and uses Html.EnableClientValidation to turn on the client side validation and Html.ValidationMessageFor to show validation messages:
<%@ 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" />
<% } %>
And in your controller method Get method to display the view:
[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
}
and in your controller Post method check use ModelState.IsValid to check if the view data is and if not add model state errors to appear on the view page:
[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");
}
In this case I simply add a model state error and then redirect to the controller Get method which will show the view again with the model error (that is what the Html.ValidationSummary code in the view does - show the model state errors automatically).
I hope this helps.
精彩评论