n00b
n00b

Reputation: 4737

ASP.NET MVC - Make a property required, but not from view

If I have an MVC model that (grossly simplified) looks like this;

public class Person
{

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

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

}

However, only the Name comes from the view. The SpecialSauce is provided server side.

person.SpecialSauce = "Ketchup"; //Hard-coded for example

However, before I save, I check ModelState.IsValid, which returns false, with the error "The SpecialSauce field is required."

How do I make the ModelState valid when the required model property is provided server side? I could remove the [Required] data annotation, but I want the EF database column to be non-nullable.

Upvotes: 0

Views: 1365

Answers (1)

Grizzly
Grizzly

Reputation: 5943

Frankly, not quite sure how you expect SpecialSauce to be required but yet not allow the user to enter a value for SpecialSauce on the form and then you override it in the controller.

But.. here is an answer if SpecialSauce needs to be required.

Since you are setting person.SpecialSauce on the server side, you should set it in the HttpGet Method. Then return the entire object back to the View. If you don't want a user editing that field, then disable it via HTML or jQuery.

Here is an example:

Controller

// GET: ControllerName/Create
public ActionResult Create()
{
    var myPerson = new Person()
    {
        SpecialSauce = "Ketchup"
    };

    return View(myPerson); // assuming your view is named Create and it is expecting an object of type Person.
}

View

@model Project.Models.Person // top of view

@Html.HiddenFor(model => model.SpecialSauce) // you can't submit disabled items to the server so create a HiddenField to hold the actual value for submission

@Html.TextBoxFor(model => model.SpecialSauce, null, new { @class = "form-control", @disabled = "disabled" }) // the textbox on page load should contain "Ketchup" and be disabled so the user can't edit the string

Then, your ModelState will be valid and then you don't have to set it in the HttpPost action method.

Let me know if this helps.

Upvotes: 1

Related Questions