0
votes

I have a very simple model. I have a location that has 2 fields, Id and Name. I have InventoryItems that has a number of scalar fields with a FK to the location at which it is stored. I have a View for creating an InventoryItem. The view has a drop down for `

<div class="editor-label">
    @Html.LabelFor(model => model.Location)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Location.Id, new SelectList(ViewBag.Locations, "Id", "Name"))
</div>

The controller code checks ModelState.IsValid which is returning false because the NAME of the location in the ModelState is empty. I really only need the Id to save the InventoryItem. But I have [required] in the Location Name field because when I go to allowing the addition of Locations, I want that field required.

Can someone tell me the CORRECT way to deal with this in the MVC design pattern?

2

2 Answers

0
votes

Well if the name is already set before this point you could just use a @Html.HiddenFor() to hide the name on the page it keeps the value for the HttpPost.

If this isn't the case then I suggest dropping the required requirement on the name in the model itself and use it on a View Model, this way you can have two different levels of validation, just bare in mind you need to make sure that if the field isnt populated at the point where it's needed it will error.

Personally I would use View Models whenever you have changing validation requirements

0
votes

The best way to go about it is to use ViewModel that have only the fields you need on the UI side and then convert to your actual Model in the controller.

In your case, you could use a LocationLink in your View/Form that only takes an Id like:

public class LocationLink
{
    [Required(ErrorMessage = "No id provided")]
    public string Id { get; set; }
}

Then in your controller you load the appropriate Location from your data store with the supplied Id and add that to the parent model.

Usually you should have a ViewModel for Display with all the fields (Locationwith Id and Name) and a ViewModel for create/edit forms (LocationLink in that case with only Id).