1

I want to create field validation in my razor view.
This is quite easy because the MVC will automatically generate the validationMessageFor for us.

As what I have read that, we are not allowed to make the validation in model class, instead use viewModel class. Now I am little confuse on how to put the [Required] annotations in my viewModel.

My problem

This is how the real validation will work
View

<tr>
            <td>Name</td>
            <td colspan="2">
                @Html.EditorFor(model => model.reg.registerNm, new { @class = "TextBoxAsLabel" })
                @Html.ValidationMessageFor(model => model.reg.registerNm)
            </td>

        </tr>

ViewModel

public class reg
{  
   [Required]
   public string registerNm {get;set;}
}

This will work, but in my ViewModel, the structure is different because I need to use data from many table

My ViewModel

    public class RegisterInfoPA
{    

    public register reg { get; set; }

    public personalInfo pinfo { get; set; }

    public IEnumerable<maritalInfo> minfo { get; set; }

    public IEnumerable<eduInfo> edInfo { get; set; }

    public IEnumerable<monthlyIncome> monthlyIncomeInfo { get; set; }

    public refundBank refundBK { get; set; }

    public IEnumerable<accType> accType { get; set; }  
}

so whenever I assign [Required] annotations here, the validation will not working.
How can I do validation message for my ViewModel, because my viewModel is using

public register reg { get; set; }

which represent so many fields, which I want, but for validation purpose, I only want one or two certain field to be validated.How can I achieve that?

Thank you .

10
  • 1
    Assuming register here is one more class, why don't you move those 2 fields to separate class and inherit them in required classes? Jun 10, 2016 at 3:36
  • 1
    A view model should not contain properties which are data models. You need to create view models for each of your data models/collections - e.g. public registerViewModel reg { get; set; }, public IEnumerable<maritalInfoViewModel> minfo { get; set; } etc.
    – user3559349
    Jun 10, 2016 at 3:41
  • 1
    Please, follow C# coding standards and naming conventions if you want other people to easiliy read your code. To be precise, do not use LowerCamelCase for properties. Jun 10, 2016 at 3:44
  • 1
    It is all about how you'd like to keep your ViewModel. I suggest you can have a property for the registerNm directly in your Viewmodel and have it back to reg when it is sent to db.
    – KDR
    Jun 10, 2016 at 3:52
  • I will try each of your suggestions and will get back soon, and see which one is working for me. Jun 10, 2016 at 7:18

0

Your Answer

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