Validations in MVC 4

0

How can I add validation to an @Html.Textbox in a View Details. This is the code.

@using (Html.BeginForm()) {

    @Html.ValidationSummary(true);
    @Html.TextBox("Referencia");

    <input value="Referencia" type="submit">


<fieldset>
    <legend>Vidrio</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Número_Material)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Número_Material)
    </div>

The Model is an Entity Framework Database First.

HomeController:

    [HttpPost]
    public ActionResult MostrarInfo(FormCollection form)
    {

        if (ModelState.IsValid)
        {
            string referencia = form["Referencia"];
            var item = db.Vidrios.SingleOrDefault(i => i.Referencia == referencia);

            return View(item);
        }
        else {

            return View();

        }
    
asked by user37511 11.04.2017 в 04:31
source

1 answer

1

There are several things to check. Some of them, as fredyfx says, may not be seen in the text you show us.

If your model is created by the Entity Framework, it will most likely come with the required attribute. For your reference:

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

Once this point is established, it will be necessary to comment that your @Html.TextBox ("Reference"), although it is named as 'Reference' does not really refer to the ownership of your model / class. What you need to do, is equal to what you do with your property Number_Material. Then, you should have something like this:

@Html.TextBoxFor(model => model.Referencia)

On the other hand, to run the validation on the client side, you need to add javascript routines. I recommend you use the easiest one:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
    
answered by 11.04.2017 / 19:37
source