0

How can I add a simple validation in my code? If value = 0 I don't want the controller to process the form. If anything else is selected except 0, I want the controller to process the form.

@using (Html.BeginForm("GenerateReport", "Admin", FormMethod.Get))
{
    <select id="reportId" name="reportId" class="form-control">
        <option value="0">Select</option>
        <option value="1">Religion</option>
        <option value="2">Address</option>
        <option value="3">Job</option>
        <option value="4">Degree</option>
        <option value="7">Age</option>
    </select>

    <input type="submit" value="Print" id="rlist_type" />
}

1 Answer 1

1

This article provides basic information on ASP.NET MVC 5 validation http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation

I would leave the value for the first option empty then add a [Required] attribute on the object that I was using to capture the form post.

public class AdminScreenFormPost
{
    [Required]
    public int reportId { get; set; }
}

Inside the controller add

if (!ModelState.IsValid)
{
    return View();
}

In the razor view add this so it will displays the validation results

@Html.ValidationSummary(true)

I would also look into ModelState.AddModelError

ModelState.AddModelError("MyDropDownListKey", "Please Select");
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! super thanks @Nathan Smith. Now it's working :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.