Add a second item to @html.textboxfor()

67 views Asked by At

I have a TextBoxFor that is set to read only and it currently holds a person's last name. What I now need to do is add to it so that the person's suffix (II, III, Sr., Jr., etc) shows in the text box next to their last name. This is what I have so far with just the last name. I can't figure out how to add the suffix portion to it (m.Person.Suffix). Everything I have tried has caused an error.

<div class="control-group">
    <label>Last Name</label>
    <div class="controls">
        @Html.TextBoxFor(m => m.Person.LastName, new { @readonly = "readonly" })
    </div>
</div>
2

There are 2 answers

0
Brisbe On BEST ANSWER

One possibility to do this, if this will always be readonly, would be adding this to your model:

public string LastNameWithSuffix
{
    get { return String.Format("{0} {1}", Person.LastName, Person.Suffix); }
}

Then you can just change your code in the textbox to reference m.LastNameWithSuffix directly:

<div class="control-group">
    <label>Last Name</label>
    <div class="controls">
        @Html.TextBoxFor(m => m.LastNameWithSuffix, new { @readonly = "readonly" })
    </div>
</div>
0
Eli On

I believe this may only be achieved through using a viewmodel. In your controller, instead of passing the original data model, you would pass the viewmodel, (used in your view) and one the entities of the viewmodel would contain the combination.

public class ViewModel
{

public string LastName {get; set;}
public string Suffix {get; set;}
public string Combo {get; set;

//rest of data needed for view
}

This would be my way of approaching this, although there are possibly other methods.