serefbilge
serefbilge

Reputation: 1714

How to pass multiple parameters dynamically into Html.Action in Asp .Net MVC

I have parameters to send like

@Html.Action("actionName", "controlName", new{ pName1 = "pValue1", ... })

But, pName1 = "pValue1", ... will come with ViewBag from a controller. What should type of object encapsulated with ViewBag, and how can I set route values into Html.Action?

Upvotes: 4

Views: 20787

Answers (1)

Alaa Masoud
Alaa Masoud

Reputation: 7135

The type of object can be anything you like from primitive types such as int, string, etc... to custom objects.

If you have assigned a value to ViewBag such as:

public class CustomType {
  public int IntVal { get; set; }
  public string StrVal { get; set; }
}
...
ViewBag.SomeObject = new CustomType { IntVal = 5, StrVal = "Hello" }

You can invoke it simply as:

@Html.Action("SomeAction", "SomeController", new { myParam = @ViewBag.SomeObject })

And in your controller:

public ActionResult SomeAction(CustomType myParam ) {
  var intVal = myParam.IntVal;
  var strVal = myParam.StrVal;
  ...
}

However, note that you can still access ViewBag from within your controllers without having to pass them in route values.

Does this answer your question?

Upvotes: 6

Related Questions