Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Partial with separate Controller and View

I've developed ASP.NET Forms for some time and now am trying to learn MVC but it's not making total sense how to get it to do what I want. Perhaps I need to think about things differently. Here is what I'm trying to do with a made up example:

Goal - Use a partial file, which can be placed anywhere on the site which will accept a parameter. That parameter will be used to go to the database and pass back the resulting model to the view. The view will then display one or more of the models properties.

This isn't my code, but shows what I'm trying to do.

File: Controllers/UserController.cs

[ChildActionOnly]
public ActionResult DisplayUserName(string userId)
{
MyDataContext db = new MyDataContext()

var user = (from u in db.Users where u.UserId = userId select u).FirstOrDefault();

return PartialView(user);
}

File: Views/Shared/_DisplayUserName.cs

@model DataLibrary.Models.User

<h2>Your username is: @Model.UserName</h2>

File: Views/About/Index.cshtml

@{
    ViewBag.Title = "About";
}

<h2>About</h2>

{Insert Statement Here}

I know at this point I need to render a partial called DisplayUserName, but how does it know which view to use and how do I pass my userId to the partial?

It's what I expect is a very basic question, but I'm yet to find a tutorial which covers this.

Thanks in advance for your help.

like image 209
McGaz Avatar asked Mar 01 '13 15:03

McGaz


2 Answers

You should call Html.Action or Html.RenderAction like:

@Html.Action("DisplayUserName", "User", new {userId = "pass_user_id_from_somewhere"});

Your action should be like:

[ChildActionOnly]
public ActionResult DisplayUserName(string userId)
{
    MyDataContext db = new MyDataContext()

    var user = (from u in db.Users where u.UserId = userId select u).FirstOrDefault();

    return PartialView("_DisplayUserName", user);
}

This should do the trick.

like image 162
Husein Roncevic Avatar answered Sep 18 '22 21:09

Husein Roncevic


I always make sure to close the MyDataContext... Maybe enclose everything in a using statement... If you notice when VS does it for you they create the entity as a private variable in the Controller Class (outside of the controllers) and then close it with the dispose method... Either way I believe you need to make sure those resources are released to keep things running smooth. I know it's not in the question but I saw that it looked vulnerable.

like image 43
Michael Puckett II Avatar answered Sep 22 '22 21:09

Michael Puckett II