Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel with complex property

I am unsure how I can get this to work. I dont know how I can create [Display(Name = "XXXX")] for my Customer properties on this ViewModel:

public class CreateAccountViewModel
{
    [Required]
    public Customer Customer { get; set; }

    [Required]
    [Display(Name = "Username")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    public string ConfirmPassword { get; set; }
}

Should I create a ViewModel for Customer and reference that instead of the Customer object? And then create Display() for all of the properties?

If so, will the mapping work on submit?

I use this as follows (snippet):

<div class="form-group">
    @Html.LabelFor(m => m.Customer.CompanyName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.Customer.CompanyName, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Customer.CVR, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.Customer.CVR, new { @class = "form-control" })
    </div>
</div>

And the "CompanyName" I wish to change to something more nice like "Company name". :-)

like image 353
janhartmann Avatar asked Dec 24 '13 12:12

janhartmann


1 Answers

As usual if I need to display some complex model with such sub objects - I create another model for this object, specify attributes in new model. And then specify this model instead of Customer property.

@Html.LabelFor(m => m.Customer.CompanyName, new { @class = "col-md-2 control-label" })

Should work fine for sub models, if it has Display attribute.

Another way is to specify these attributes under your domain classes, but as for me - i don't like to dirty domain objects with UI attributes

like image 168
Sergey Litvinov Avatar answered Oct 23 '22 02:10

Sergey Litvinov