asp.net-mvchtml-helperhtml.textbox

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.

  1. use the @value initializer and an inline IF statement

    Html.TextBoxFor(m => Customer.City, new { @Value = somecondition ? CustomerApprove.City : Customer.City })

  2. 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?


Solution

  • 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; }
    }