I have the following viewmodel in my mvc project.
public class AddGISViewModel
{
public myproject.Models.DomainModels.GIS gis { get; set; }
public IEnumerable<myproject.Models.DomainModels.Companies> Companies { get; set; }
public long CompanyID { get; set; }
}
I have created a view as this
@model myproject.ViewModels.GIS.AddGISViewModel
@using (Ajax.BeginForm("Create", "GIS", new AjaxOptions { HttpMethod = "Post", Url = "/GIS/Create" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.Label("company", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CompanyID, new SelectList(Model.Companies, "CompanyID", "Name"), "select company please ", htmlAttributes: new {@class = "form-control" })
@Html.ValidationMessageFor(model => model.CompanyID)
</div>
</div>
also I have created following metadata
[Required(ErrorMessage = "you should select company")]
[DisplayName("company")]
[Display(Name = "company")]
public long CompanyID { get; set; }
When I run my project @validationmessagefor show 'CompanyID is a required field' not 'you should select company' that I define in metadata. How can I fix this problem?
You have created a view model, so apply those attributes to the property in the view model. Since the purpose of a view model is to represent what you want to display/edit in the view there is no point creating a separate class for metadata.
Your view model should be
public class AddGISViewModel
{
[Required(ErrorMessage = "you should select company")]
[DisplayName("company")]
public long? CompanyID { get; set; }
public IEnumerable<SelectListItem> Companies { get; set; }
....
}
Note that the CompanyID
property should be nullable to protect against under-posting attacks, and the collection property for displaying the companies n the dropdownlist should be IEnumerable, so that the view is
@Html.DropDownListFor(model => model.CompanyID, Model.Companies, "select company please ", new { @class = "form-control" })
In addition, view models should not contain data models if your editing any properties of that model. If so replace GIS gis
with each property of GIS
that you need in the view.