0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.