[RESOLVED]Viewmodel validation in asp.net mvc

Hi,

I have an asp.net mvc form. The form uses jquery to post the data and a viewmodel is bind to it. To validate the form, I am using the in-built data annotation attributes. But this does not seem to work with a view model. Please help me here. Below is my
sample code for the view and viewmodel.

Thanks.

@using (Html.BeginForm("AddProject", "Project", FormMethod.Post))
{ 
    @Html.ValidationSummary(true)
    
    <table cellspacing="5" cellpadding="10">
<tr>
<td>@Html.HiddenFor(model => model.ProjectID)</td>
</tr> <tr> <td>Project Year:</td> <td>@Html.DisplayFor(model => model.ProjectYear)</td> </tr> <tr> <td>Project Name:</td> <td> @Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name) </td> </tr> <tr> <td>Description:</td> <td>
@Html.TextAreaFor(model => model.Description, 5, 30, new { style = "spellcheck: false;" })
@Html.ValidationMessageFor(model => model.Description)
</td> </tr> <tr> <td><input type="button" value="Submit" onclick="SubmitForm();" /></td> </tr> </table> }

Viewmodel

namespace ProjectStatus.ViewModels
{
    public class ProjectViewModel
    {
        private ProjectEntities db = new ProjectEntities();

        public int ProjectID { get; set; }
[Required] public string Name { get; set; }
[Required] public string Description { get; set; }
public short ProjectYear { get; set; }
public ProjectViewModel() { } public ProjectViewModel(Projects prj) { ProjectID = prj.ProjectID; Name = prj.Name; Description = prj.Description; ProjectYear = prj.ProjectYear; } } }

Try this:

 @Html.ValidationSummary(false)

Note you can also try @Html.ValidationSummary

You should also be able to put a break point in the controller method to see what values are being returned.

@v2kea60

I tried it, but that does not seem to solve the issue.

Please include the below 2 scripts and reference it in your view.

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Hi User220,

According to your description, I would like to know how do you use JQuery to post data.

First, please refer to asif’s reply.

Secondly, if you are using the AJAX to submit the data, please call valid() method to do validate.

$("Form").valid();

Best Regards

Starain Chen

Leave a Reply