Dr. Dorian White
Dr. Dorian White

Reputation: 165

Client Side Validation for Hidden Input in ASP.NET MVC

I'm still a bit novice to the ASP.NET MVC architecture. I have an Edit page for data, which includes a hidden input. After testing my page, the 'Save' button wasn't doing anything and after some research learned it was a client-side validation issue.

After commenting the following line in the page:

 @*@Html.HiddenFor(model => model.ID)*@

(where ID is a GUID), the page validated and posted.

From what I recall, the scaffolding put this code into my view. I just need to know how to fix this so that the ID field gets sent back properly to the controller and wanted to know why it wasn't validating.

Here is my View's code:

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

    <fieldset>

        <div class="object_basics">
      @Html.HiddenFor(model => model.ID)

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


       <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

}

Upvotes: 0

Views: 1554

Answers (3)

Mojtaba
Mojtaba

Reputation: 1620

Client side validation for hidden fields not working, because jQuery validation ignore all hidden tags.
You must define HiddenRequiredValidator class to achieve your goal.

You can read a solution to solve this problem Here

Upvotes: 1

Shani Elharrar
Shani Elharrar

Reputation: 657

Have you tried to add the validation message for the ID ?

@Html.ValidationMessageFor(model => model.ID)

Upvotes: 1

DannyM
DannyM

Reputation: 1

In view, update from:

@using (Html.BeginForm()) 

To

@using (Html.BeginForm(new{ID = model.ID})) 

Remove the hidden element [@Html.HiddenFor(model => model.ID)].

In your controller, update the action properties like below

public ActionResult YourActionName(string ID, string Title)

Hopefully, this answers your question.

Cheers, Danny

Upvotes: 0

Related Questions