Gonzalo
Gonzalo

Reputation: 992

Passing a string (besides the model) into a partial view in MVC4

How can I send a string to a partial view?

What I would like is to send information about the model being viewed, to a partial view. Something like this:

@{Html.RenderPartial("_PhaseCreate", new Phase(), @Model.Id );}

Is this possible?

Upvotes: 1

Views: 8200

Answers (1)

Amin Saqi
Amin Saqi

Reputation: 18977

If you want to send some data that isn't in model or view, you should use something like the following:

1) instead of @Html.Partial(), use a @Html.Action("ActionName", "Controller", routeValues: new { id = Model.Id }) helper.

2) Add something like this to your controller:

public ActionResult GetMyView(int id)
{
    ViewBag.Phase = new Phase();
    ViewBag.Id = id;
    // also whatever which doesn't in model ...

    return View("_PhaseCreate");
}

And in your partial view, you can use those info just like you declare them:

<label>@ViewBag.Id</label>

You also can simply use the following if you just need to add data existing in model and the view:

@Html.Partial("_PhaseCreate", 
              new ViewDataDictionary(new { Phase = new Phase(), Id = Model.Id }))

and use them like this:

<label>@ViewData["Id"].ToString()</label>

Upvotes: 2

Related Questions