Parminder
Parminder

Reputation: 3158

Html.Action asp.net mvc

I am working on a website (Asp.net mvc), where I have multiple partial views. One of the views is user information and then below there are few other views say books by the user, articles in a given book etc. thats how my controller looks like.

public class UserController : Controller
{

   public ActionResult UserInfo(long userid)
   {
        var model.User = LoadUser(userId);
        return View(model);
   } 

   public ActionResult Books(long userId)
   {
        var model.User = LoadUser(userId);
        model.Books = LoadBooks(userId);

        return View(model);
   } 

   public ActionResult Articles(long bookId)
   {
        var model.User = LoadUserByBookId(bookId);
        model.Book = LoadBook(bookId);
        model.Articles= LoadArticles(bookId);

        return  View(model);
   } 

} 

I have created three partial views for UserInfo, Books and Articles and pass data from a given view. Now you can see with each method things go more complex. I was reading about Html.Action helper which can load individual partial views. But as you can see I need to pass some data from Html.Action helper to the methods so it can load data accordingly for example to load userinfo, I will need to pass userId.

How can I achieve this using this or any other better method. Help will be appreciated.

Regards Parminder

Upvotes: 2

Views: 8850

Answers (2)

Ahmad
Ahmad

Reputation: 24947

It seems to me the that Lance provides the final step of this solution. Obviously, if Html.RenderAction is used as he describes there must be another Controller Action which has already been invoked, since we now Rendering Actions (Partial views) in a larger view.

What I think you need is a ViewModel which needs to be populated in the main controller action

public class PageInfo
{
    public long UserId { get; set; }
    public long BookId { get; set; }
}

with the main action

....
public ActionResult MainAction()
{
     // you probably have some logic here that gets the actual userid and bookid

     PageInfo theModel = new PageInfo(){UserId = 39894, BookId = 3};
     return View(theModel);
}

And then in when calling the RenderAction within the MainAction page

<%: Html.RenderAction("Articles", new { bookId = Model.BookId }) %>
<%: Html.RenderAction("UserInfo", new { userId = Model.UserId }) %>
<%: Html.RenderAction("Books", new { userId = Model.UserId }) %>

Upvotes: 1

Lance Fisher
Lance Fisher

Reputation: 25823

In a view, Html.RenderAction() will execute the controller, and then render it's returned view as a partial. you can use it like this:

<%: Html.RenderAction("Articles", new { bookId = 3 }) %>

The first argument, "Articles" is the name of your action method, the second argument is a C# anonymous object. We create a bookId property and set it to 3. That will render the Articles view returned from the Articles action method into your current view. Good luck!

Upvotes: 2

Related Questions