5

I want to Merge this two dislpay

  <td>
        @Html.DisplayFor(modelItem =>  item.CustomerFirstName)
  </td>
  <td>
        @Html.DisplayFor(modelItem => item.CustomerLastName)
  </td>

into like this

  <td>
        @Html.DisplayFor(modelItem => item.CustomerFirstName && item.CustomerLastName )
  </td>
4
  • You cant. Either add a property to your view model that concatenates both values or put the 2 x DisplayFor() in the same <td> element Commented Mar 15, 2017 at 12:28
  • My model is from SDK so I can't modify it Commented Mar 15, 2017 at 12:33
  • That's why we use view models Commented Mar 15, 2017 at 12:35
  • if your model had something formatted on a particular field then Html.DisplayFor(...) comes in handy (e.g. [DisplayFormat(DataFormatString = "{0:d}")]). In this case though (and as you can't/don't want to edit the model) why not just have: <td>@item.CustomerFirstName @item.CustomerLastName</td> Commented Mar 15, 2017 at 12:41

4 Answers 4

8

Use code block to concatenate the first name and last name then pass result to DisplayFor as shown below.

 <tr>
    <td>
    @{
        var fullName = Model.CustomerFirstName + " " + Model.CustomerLastName;
        @Html.DisplayFor(m=>fullName)
    }
    </td>
 </tr>

HTH

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

Comments

2

We can write like

@Html.DisplayFor(modelItem => item.LastName), @Html.DisplayFor(modelItem => item.FirstName)

Comments

1

You can always for something like this:

<label>@Html.Raw(string.format("{0},{1}",Model.CustomerFirstNAme,Model.CustomerLastNAme))</label>

Comments

1

Short Answer, no you can't do that.

If you can't modify it from the SDK, use ViewModels, map the SDK entities to your ViewModels and merge firstname and lastname together in your controller before passing it to the view.

View Model:

public class YourViewModel
{
     public string FullName { get; set; }
}

Controller:

public ActionResult YourController()
{
    var model = new YourViewModel {
        FullName = FirstName + LastName //from your SDK
    };

    return View(model);
}

Then you can do this in your View:

@model xxx.YourViewModel

@Html.DisplayFor(m => m.FullName)

Or, why don't you just do this?

<td>@Html.DisplayFor(modelItem => item.CustomerFirstName) @Html.DisplayFor(modelItem => item.CustomerLastName)</td>

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.