ASP.NET MVC Html.TextBoxFor dynamic value
I have a scenario where on a certain view I can have 2 different objects of the same type [Customer]
. The first one is called Customer
, the other one is called CustomerApprove
. The latter contains a change in the customer data to be approved.
If the CustomerApprove
object is filled, I want the textbox to contain that value. Otherwise I want to use the normal Customer
object value.
I thought of 2 ways to achieve this.
use the @value initializer and开发者_运维技巧 an inline IF statement
Html.TextBoxFor(m => Customer.City, new { @Value = somecondition ? CustomerApprove.City : Customer.City })
Call a method on the Model to determine which object to use.
Html.TextBoxFor(m => Customer.City, new { @Value = Model.SomeMethodToGetTheValue() })
Which is the better approach to use, or are there any other suggestions?
I would recommend you using a view model and populating the corresponding property in the controller so that in the view you could simply:
@Html.TextBoxFor(x => x.CustomerCity)
In the controller action based on the values of the model you will populate the CustomerCity
view model property respectively.
How about creating View model for both Customer and CustomerApproved. ViewModel will expose some common properties (eg. City), and you simply return ViewModel from your controller instead. I'm thinking about something along those lines:
public class CustomerViewModel
{
public CustomerViewModel(Customer customer)
{
this.City = customer.City;
}
public CustomerViewModel(CustomerApprove customerApprove)
{
this.City = customerApprove.City;
}
public object City { get; set; }
}
精彩评论