Share via


How to access ViewBag/ViewData in Web API controller (VB.NET)

Question

Sunday, January 20, 2013 10:52 PM

Hello:

I am new to Web API, please bear with me if my question sounds kinda stupid.

Here I am working on a Web API controller (using VS2010 VB.NET), I am just playing around trying to access ViewBag or ViewData, but none of the two intellisense recognizes, only ViewPage accessiable, however I don't know what does ViewPage do.

as sample as:          ViewBag.messsage("hello")

So is it Viewbag/ViewData only applicable to MVC controller, not Web API controller?

I am using ASPX view engine, not Razor, so from ASPX page, how to access data returned from Web API Controller?

Please advise,

Thank you

All replies (2)

Monday, January 21, 2013 8:54 AM âś…Answered

If you want to render content, you should use MVC. Web API provides a new mechanism for generating web apis/services that gives you better control over HTTP. (You can create HTML sites with Web API, though you won't get the bells and whistles offered by MVC out of the box.)

ViewBag and ViewData are only accessible within MVC controllers (derived from System.Net.Mvc.IController). Web API controllers, while similar in appearance, are unrelated and use an altogether different model. They implement System.Web.Http.Controllers.IHttpController.

I have no idea where you see ViewPage. I don't have that property or type available in the Web API controllers in my project. I think ViewPage is a base class for MVC views.

To access data returned from a Web API controller, you need to either model bind it in the controller actions or read it from the this.Request.Content object. See the tutorials for more info.


Monday, January 21, 2013 10:15 AM

Thank you so much for your detailed explainations!! really apprecate!

although I've already watched tutorial video, I still having problem understand what you said "model bind it in the controller actions"

my data model is Stored Procedure only, ie. Get a list of something, or Get something by ID, etc. then from aspx page, I use JQuery ajax call, like this:

 $.ajax({
  url: "api/xxxxx/getAll",
  contentType: "json",
  success: function (data) {
      //do something with data here....
  }
});

is this what you mean "model bind it in the controller actions"? how else to access it?

would you mind point me to an example using this.request.content?

Thank you,

Here is the ViewPage