开发者

Can you put a PartialView into a ViewData object?

I'm trying to mimic the webforms 开发者_Go百科multiview functionality and the only way i can think of is to put a PartialView into a ViewData object? Something like the following:

View code:

<%= ViewData["PartialViewPlaceholder"] %>

Controller code:

if(//condition){    
    ViewData["PartialViewPlaceholder"] = partialView1;
} else {
    ViewData["PartialViewPlaceholder"] = partialView2;
}

How would you go about this?


ViewData is meant to contain actual data, not views themselves, which contain markup and rendering code. Would it not be possible for you to do this:

public ActionResult MyActionMethod()
{
    var model = new MyModel();
    model.UsePartialView1 = false; // Tell the view not to use Partial View 1
    return View("MyView", model);
}    

And in the View MyView:

<% if (Model.UsePartialView1) 
       Html.RenderPartial("PartialView1", Model);
   else
       Html.RenderPartial("PartialView2", Model); %>

This will render either PartialView1 or PartialView2 using the same Model depending on the condition set by the Controller.

Or, to return a Partial View with a Model directly from your controller, instead of a normal View, you can do this:

public ActionResult MyActionMethod()
{
    var model = ...
    ViewData["MyViewData"] = ...
    return PartialView("PartialView1", model);
}

This will return the Partial View PartialView1 directly to the client. This is mostly useful in AJAX scenarios, since the result will most probably not be an entire HTML page. Partial Views are .ascx files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜