How to render Web Api to a view? - asp.net-mvc-4

I wrote some code in webapi ValueConroller. When I try to execute it I'm getting JSON data which is by default saving to text file (IE 8.0), XML output when tried with Mozilla Firefox .
I am not sure how to display my List<country> which will be having list of countries and i am writing this method in value controller like
public IEnumarable<countrylist> getcounrty()
{
obj.method1().tolist(); // method1 will return list<country> where country is a class in my BLL
}
I want the method output to be bonded with Dropdownlist . Becoz there is no VIEW is webapi I am confused how to do it
Any ideas are appreciated.
EDIT : konckout.js is a alternative ? my colleagues ad-viced me so any best alternative mates

Web API and MVC have different purposes.
The purpose of ASP.NET Web API is to build HTTP-based web services (also sometimes called REST services). Out of the box, it only supports
JSON
XML
although you can implement other formatters yourself, if you need to exchange data in another format. In theory, you could write a custom formatter to produce HTML, but there's no reason to do that.
If you need to produce HTML, then use ASP.NET MVC.

Related

What is the purpose of AddFormatterMappings() on Asp.net Core 2

I am evaluating the configuration of a Web API App with Asp.Net Core 2. To configure I know it is better for my project to use .AddMvcCore() rather then use AddMvc() since I don't need Razor as we can see here.
Now, I am not sure if I also need this .AddFormatterMappings(). So my question is what is it for?
You can see from the source code in the MVC GitHub repo that it adds a FormatFilter service into the DI setup. The summary for the FormatFilter class is as follows:
A filter that will use the format value in the route data or query
string to set the content type on an ObjectResult returned from an
action.

JSON.NET MVC 4 WebApi proper return type

I see different examples of different return types for WebApi Controller.Method.
Customizing JSON.NET serialization- Get method returns HttpResponseMessage
using JSON.NET in ASP.NET MVC - shows ActionResult (I understand it is outdated article)
Web Api Tutorial returns Business object
I wonder what are the guidelines when to return what?
Thank you.
That all depends on your requirement.
when you return HttpResponseMessage, it gives you options to return HttpStatusCode with a custom message.
Say for example, in your application, you are saving something through web api (say a new customer for example). you can return that object with the message as well pretty easily and you don't have to worry about the return type (json or xml) at all. And this will be an answer for your 3rd point as well. This is the better way to send a business object to the frontend in web api.
as an answer to the 3rd point, please take a look at this blog post for more info. http://blogs.msdn.com/b/yaohuang1/archive/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples-on-the-help-page.aspx
in a web api action which return an HttpResponseMessage, the return code would look something like this.
return Request.CreateResponse<Customer>(HttpStatusCode.Created, newlyCreatedCustomer);
The second post doesn't mention anything about web api. It shows a way to return json data if you ever want to do it in the Controller Action.

What is an efficient way to create/manage RESTful API with grails?

I've built my first grails application. My URL mappings are what the default application provides:
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
Senario
I have a controller called ColorController with actions save and list. It simply does something like this:
def save () {
def colorInstance = new Color(params)
colorInstance.save(flush: true)
}
def list () {
[colorList: Color.list, colorTotal: Color.count()]
}
I would like to build a simple API for these actions.
The save action should accept parameters as JSON and provide a successful message if the records save.
The list action should provide the list as JSON
Questions
Should I make a separate URL mapping for api? (e.g. http://<domain>/<app>/rest/controller/action)
Should I be making a separate controller for my API's
I am using spring security plugin for authentication. But at some point I might want to authenticate the restful api as well. What are some solutions for that?
If I use the same controller, how can I modify these simple actions to do what I need.
Before even looking below for my opinion/answers I would suggest to visit this SO Question for the basic understanding of RESTful WS in Grails.
Opinions:
"The save action should accept parameters as JSON and provide a successful message if the records save" - Save is mapped to POST RESTful. Instead of binding a JSON body to params it is bound to the request. In order to access the JSON object you just need to use request.JSON in the action method.
request.JSON instanceof JSONObject
"The list action should provide the list as JSON" - list() action is mapped to a GET Request and you can render the map as JSON in the list() as below
//Controller list()
import grails.converter.JSON
def list () {
[colorList: Color.list, colorTotal: Color.count()] as JSON
}
Answers to Questions:-
Should I make a separate URL mapping for api?
Abiding by the basics of REST, the client should only access the resource (Color in this case) and should not bother about the underlying controller or action. The server side logic should be abstracted from the client. URL Mapping is what the client would use to as form of request. I would have something like this in my url mapping for Color Resource.
/color/$id?(resource: "color")
or
/color/$id?(controller: 'color'){
action = [GET: "list", POST: "save"]
}
Should I be making a separate controller for my API's? - Depends on the way the App is designed. You also can have the above controller as the API. For example, currently I am working on a grails app which used AngularJS in the front End which connects to the Grails APP RESTFully. In order to achieve I had a RestClientController which works as an API to Angular. The rationale behind having a REST api in the same app is that in future we can expose the underlying service to external clients other than the Angular client present in the app itself.
I am using spring security plugin for authentication. But at some point I might want to authenticate the restful api as well. What are some solutions for that? - You can use Spring Security here as well. In my case I am using the plugin and I secure the controller by using the plugin's annotated component #Secured. I have custom OAuth enabled as well for authorization which interacts to the company wide LDAP and AD Groups.
If I use the same controller, how can I modify these simple actions to do what I need. - I think you would have got the answer to this question by now (after going through the SO question I mentioned above). Here is my opinion, controller actions can route to appropriate service classes which does the business implementations based on the request parameters.
For example,
//Action
def show(){
if(params.id){
colorService.getColor()
} else {
colorService.searchColor()
}
}
In the above example, the url mapping would be /color/123 or /color. In the former case, it will get the color and in the later it will search the colors

Dynamically create json using WCF service to feed MTDialog application

I wish to create a MonoTouch MTDialog-based app that upon launching adds a single element to the MonoTouch Dialog and then render the screen. This single element will be a JsonElement similar to this -
var je = new JsonElement ("Dynamic Data", "http://tirania.org/tmp/demo.json");
as shown in the sample application. However, instead of referencing a pre-built json file on a server, I wish to have the url point at a WCF OData service which will dynamically build the json data.
I am not sure what is the easiest way to do this. I am a bit lost after reading over the documentation. Is there some library I can include in my server-side C# app which I can then use to build out the elements and return as a json string of information?
I already have a WCF application up and running and just need to add an entry point which will call the method to create some simple json data for MonoTouch dialog to consume.
Any examples or suggestions are greatly appreciated as I am trying to get a simple solution completed by this weekend.
You're looking for a C# JSON library? How about JSON.NET http://james.newtonking.com/pages/json-net.aspx
You might also look at ServiceStack.NET -- they have a MonoTouch client.

What are the benefits of an ASHX handler file in asp.net?

What are the benefits of using an ashx, or handler? Also, do I need them if I use MVC (and why not)?
Does the framework matter (2.0+)?
Why would I want to use a handler? I was recently recommended to use one for retrieving an image but I don't know why.
Thank you for your time.
Edit - is a handler faster?
Just a few examples:
Dynamic image generation: You can write handlers that return data driven images by creating an ASHX handler that returns image data and then using that URL in your tags. e.g. <img alt="user's custom icon" src="Icon.ashx?username=bob"></img>
Returning REST-based XML or JSON data to AJAX code on the client.
Custom HTML: Return totally custom HTML for a page when the ASP.NET Web Forms or MVC framework is too restrictive
I believe this has been available since 1.0
The purpose of handlers in non-MVC projects is to provide some type of encoded response, outside of HTML. Typically, a handler would return XML (rss, RESTful, etc), JSON for jQuery or other Javascript, or sometimes just pure data such as file binary downloads. I've used handlers to even return special javascript to be excuted on the client, as a way of lazy-loading large binary or requirements on a "demand-only" approach. More or less, a handler would be used to return "anything but HTML".
In MVC, you would move away from handlers and utilize the Controller to return whatever data you like. So, in the method like:
mywebsite.com/restapi/content/56223
You RestfulContentController would have a method for Index(), that would NOT return a View(), but instead pure XML or JSON.
public class JSONContentController : Controller
{
public JsonResult Index(int ContentID)
{
// get Content() by ContentID
//
// return a JSON version
return Content().SerializeToJSON();
}
}
They're very useful if your working in an environment where you do not have access to IIS but want to change things like far-future expiry response headers to optimize caching for files like css, images, JavaScript
For images you can do stuff like on the fly optimization so you can request images like image.jpg.ashx?w=180&quality=70 and then use the handler to deliver the image based on the settings passed in the querystring
aspx inherits page which implements IRequireSessionState. So if you call it via Ajax then asp.net needs to lock the session before further processing.
For ashx file it is stateless.
Unless you inherit it from IRequireSessionState to manage state.
Use ashx for all Ajax calls and use aspx for purely asp.net page.