MVC 4 Partial with separate Controller and View
Asked Answered
C

2

5

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.

Colliery answered 1/3, 2013 at 15:17 Comment(0)
M
6

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.

Muriah answered 1/3, 2013 at 15:34 Comment(1)
Thanks for the fast reply & correct reply - it worked! I've tried so many deviations on the structure and @html.Options, but none worked. I knew it would be simple when you know how! Thanks again for your help.Colliery
E
1

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.

Ethyne answered 28/3, 2015 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.