Asp.net-mvc – How to pass parameters to a partial view in mvc 4

asp.net-mvcasp.net-mvc-4partial-viewsrazor

I have a link like this:

 <a href='Member/MemberHome/Profile/Id'><span>Profile</span></a>

and when I click on this it will call this partial page:

 @{
    switch ((string)ViewBag.Details)
    {

        case "Profile":
        {
           @Html.Partial("_Profile"); break;
        }

    }
}

Partial page _Profile contains:

Html.Action("Action", "Controller", model.Paramter) 

Example:

@Html.Action("MemberProfile", "Member", new { id=1 })   // id is always changing

My doubt is that how can I pass this "Id" to model.parameter part?

My controllers are:

 public ActionResult MemberHome(string id)
    {
        ViewBag.Details = id;
        return View();
    }
  public ActionResult MemberProfile(int id = 0)
    {
        MemberData md = new Member().GetMemberProfile(id);
        return PartialView("_ProfilePage",md);
    }

Best Answer

Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.

If you just render a partial with just the partial name:

@Html.Partial("_SomePartial")

It will actually pass your model as an implicit parameter, the same as if you were to call:

@Html.Partial("_SomePartial", Model)

Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:

@model Namespace.To.Your.Model

@Html.Action("MemberProfile", "Member", new { id = Model.Id })

Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary

@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });

And then:

@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })

As with the model, Razor will implicitly pass your partial the view's ViewData by default, so if you had ViewBag.Id in your view, then you can reference the same thing in your partial.

Related Topic