0

How can I pass/send a ViewBag to my DisplayTemplates? I can't use a ViewModel for this so I think on ViewBags... For example:

Part of my view:

@Html.DisplayFor(model => model.Car)

Car.cshtml (displayTemplate):

<tr>
    <td>
        @Html.TextBoxFor(model => model.Name, new { Name = modelFieldInitialName + "Name", id = modelFieldInitialId + "Name" })
        @Html.ValidationMessageFor(model => model.Name)
    </td>
    <td>
        @Html.DropDownListFor(model => model.Brand, new SelectList(ViewBag.Brands, "Description", "Description"), "", new { Name = modelFieldInitialName + "Brand", id = modelFieldInitialId + "Brand" })
        @Html.ValidationMessageFor(model => model.Brand)
    </td>
</tr>
Ninita
  • 1,209
  • 2
  • 19
  • 45

1 Answers1

1

The ViewBag is available in the View without you passing it in. If you add something to ViewBag in the Controller, it will be available in the View.

//Controller

public ActionResult Test()
{
   ViewBag.Message = "Hello World";
   return View();
}

//In The View

@if(!string.IsNullOrEmpty(ViewBag.Message))
{
  <p>ViewBag.Message</p>
}
Lotok
  • 4,517
  • 1
  • 34
  • 44
  • that seems to work to DisplayTemplates but don't work to a partialView appended to the view by an user action. You know how solve it? – Ninita Dec 18 '13 at 18:07
  • That's because the partial view is being loaded into an existing view async. In that instance I would either have the data in the ViewModel or grab it with JQuery (or JS). What are you doing that you don't think a ViewModel can handle? – Lotok Dec 18 '13 at 20:17
  • I'm creating a dynamic table here when the user want create a new table row is appended a specific partial view to it (so I can't use a viewModel for that), and how I have to call a wcf service to populate some dropdownlists I don't want to call the service everytime I create a new partial view – Ninita Dec 19 '13 at 09:34
  • Can't you store the WCF service result in JavaScript? – Lotok Dec 19 '13 at 09:36