4

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?

6
  • It's not clear what you are trying to do. Are you trying to send some data stored in ViewBag in the route values? Commented May 12, 2013 at 0:14
  • Yes. As you understood. Commented May 12, 2013 at 0:53
  • do your self a favor and avoid the view bag. the view bag is great but it is the quick and dirty answer. I strongly recommend using a defined model object to store information from the controller to pass into the view. @model someclass strongly typed views are much easier to maintain than views that rely of the view bag. Commented May 12, 2013 at 2:41
  • @jcwmoore, what is the problem with ViewBag? Commented May 12, 2013 at 9:03
  • @serefbilge, I have written applications that relied on the ViewData (predecessor to ViewBag) and applications that only used models. the latter was much cleaner and far easier to test. There is nothing wrong with the ViewBag, I just avoid it, completedevelopment.blogspot.com/2011/12/… Commented May 22, 2013 at 2:32

1 Answer 1

6

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?

Sign up to request clarification or add additional context in comments.

1 Comment

It is usable, I prefer to use it with Dictionary<string, string> type , because with string data names(keys) can be easily accessible without further definition. so one vote to you. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.