karan k
karan k

Reputation: 967

server-side mvc3 validation for form not working

I have a form in my View. The fields on the form are derived from the Model. I have just given a single variable to shorten the code here.

MODEL:
public class abc
{
    [Required]
    public string name { get; set; }
}

VIEW:
<body onload="SetButton()">
@using (Html.BeginForm("myaction","mycontroller",FormMethod.POST, new {id="myform"}))
{
    @Html.TextBoxFor(m=>m.name)
    @Html.ValidationMessageFor(m=>m.name)
}
</body>
<script type="text/javascript">
function SetButton{
    document.getElementById("button").innerHTML='<input type="submit" value="Next"             style="width:90px" onclick="myform.submit()"/>';
}
</script>

Layout Page:
<div id="button"></div>

On clicking the 'Next' button, validation does not occur. The form gets submitted even if there is nothing entered for 'name' field.If the button is put inside the Form(myform), validation works.Why isn't the validation working for the code shown?

Upvotes: 1

Views: 1443

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

Your submit button is outside of the form. This is not possible. A submit button must be placed inside the corresponding <form> element. So you will need to move the <div id="button"></div> inside the form.

If for some reason the div needs to stay outside the form (which is semantically incorrect) you need to use javascript and in this case you could use a normal button and not a submit button.

Another important aspect of html forms is that they cannot be nested. So if you have another form in your layout you cannot have a nested form inside your view. That's invalid HTML and results in unexpected behavior.

As far as the server side validation is concerned, make sure that the controller action you are posting your form to takes your view model as action argument:

[HttpPost]
public ActionResult MyAction(abc model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    ...
}

Upvotes: 2

Related Questions