deep
deep

Reputation: 215

Data validation with entity framework

I am using ADO.Net entity framework with asp.net mvc3. I have a model which is database first. The data validation does not work in some cases, as I will explain.

I have a form, when I submit that form, some items are being validated while others are not. I am simply using a form like this,

    @using (Html.BeginForm()) {
    @Html.ValidationSummary(true)


   <fieldset>
        <legend></legend>


         <div class="editor-label">
            @Html.LabelFor(model => model.VERSION_ID)
            @Html.EditorFor(model => model.VERSION_ID)
            @Html.ValidationMessageFor(model => model.VERSION_ID)
        </div>

        <div class="editor-field">
            @Html.LabelFor(model => model.ENTITY2.Name)
            @Html.EditorFor(model => model.ENTITY2.Name)
            @Html.ValidationMessageFor(model => model.ENTITY2.Name)
        </div>
    <p>
        <input type="submit" value="Create" />
    </p>

Now, the version_id has validation working while the Name does not. I am getting the name from another entity. Any ideas on why the validation is not working? I can input empty fields which should not be allowed as that field is required, but when i press submit i get an error.

Upvotes: 1

Views: 1069

Answers (1)

Shyju
Shyju

Reputation: 218702

I think your Model class is allowing empty values.

I would avoid using the Model classes directly in Views and create a separate ViewModel (a POCO class) for that. The ViewModel should have only relevant properties which the view requires. Not all the Properties of domain model most of the time !. you can use data annotations on the ViewModel( Required attribute etc...)

public class VersionViewModel
{
  [Required]
  public string VersionID { set;get;}

  [Required]
  public string Name { set;get;}
}

Your View will be strongly typed to this ViewModel. When posted back to the action method, you will map the values from the ViewModel fo your domain model and save it.

[HttpPost]
public ActionResult Edit(VersionViewModel model)
{
  if(ModelState.IsValid)
  {
     //validation is ok. Let's save
    var domainModel=new Version();
    domainModel.VERSION_ID=model.VersionID ;
    domainModel.Name=model.Name;

    //Let's save and REdirect 
    yourRepositary.SaveVersion(domainModel);
    return RedirectToAction("Saved",new { id=model.ID});     
  }
  return View(model);
}

Instead of manually mapping, you may consider using the libraries like AutoMapper.

Upvotes: 3

Related Questions