简体   繁体   中英

ASP.NET MVC 4 partial view not working

I wrote a partial method like this :

public ActionResult _StatePartial()
        {
            ViewBag.MyData = new string[] { "110", "24500" };
            return View();
        }

And render _StatePartial view in _Layout page:

@Html.Partial("_StatePartial")

This is my partial view code:

@{
    string[] Data = (string[])ViewBag.MyData;
}
<div id="UserState">
        Reputation: @Html.ActionLink(Data[0], "Reputation", "Profile") | 
        Cash: @Html.ActionLink(Data[1], "Index", "FinancialAccount")
</div>

But when I run this project, _ StatePartial method does not invoke and ViewBag always null.

Server Error in '/' Application.
Object reference not set to an instance of an object. 

Note that these parameters is not my model field and compute by calling a web service method. but I'm set these value in my question constantly.

What can I do for this? Any idea for passing parameters to partial view? Thanks.

Your call:

@Html.Partial("_StatePartial")

will render the view, but it will not call the action. You would only use this if you were seeting up all your view data in your parent page action. In your case you need to use this:

@Html.Action("_StatePartial")

This will call the action first to retrieve and execute the view.

Also:

return View();

is for returning view with Layout. You need:

return PartialView();

And I would recommend use this:

public ActionResult StatePartial()
{
    ViewBag.MyData = new string[] { "110", "24500" };
    return View("_StatePartial");
}

but better to use strongly typed models, not ViewBag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM