.net web service - c#

i am calling a web service by aspx page and wants my return output as a json format with a specific view like (grid view) in asp.net...so here is any view available in JSON which display my output like grid view..pls give me suggetion as soon as possible....thax
salman ansari

As far as I know, WebServices are based on XML SOAP objects, I anot sure if these can be handled like Json objects or converted. You could create a page (or view in MVC), that returns json objects specifically.

Related

How to serialize an object in MVC 5 Razor view

I have tried to follow this post in order to create a 3 page form wizard that passes data to each page.
He uses the HTML helper serialize, to serialize an object in the view.
#Html.Serialize("wizard", Model)
However this HTML helper isn't available in MVC 5 it seems.
I found another related post to this here where he suggests using the following to serialize the object.
#Html.Hidden("otherComplexData", new Microsoft.Web.Mvc.MvcSerializer().Serialize(complexObject))
But I then get the following error
There is no argument given that corresponds to the required formal parameter 'mode' of 'MvcSerializer.Serialize(object, SerializationMode)'
It seems to want a SerializationMode, however the documented one doesn't. https://msdn.microsoft.com/en-us/library/microsoft.web.mvc.mvcserializer.serialize(v=vs.118).aspx
What direction can I go in now?
Thanks.
Here's the Serialization option you need:
https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/MvcFutures/Mvc/SerializationMode.cs
Options are Signed or EncryptedAndSigned.
You can try that and see if it will work.
There's multiple ways to encode data that will work for you. You could put the values in a hidden input using Json.Encode for the view, and Json.Decode on the server side.

Invalid JSON when parsing objects containing html as a string property

I've got a controller action that just displays a JSON result: http://pkssblog-stage.azurewebsites.net/BlogPosts/GetAll. The object has a property called Content which is basically the HTML content of a post.
The problem is I always get invalid JSON exceptions when parsing it using the JsonObject.Parse in WinRT, the JSON.parse within a browser console or even JSON validators online.
The weird thing is that I don't get issues when I turn it into a javascript object via the console through var x = jsonstringarray;
I get in trouble with this specific property (as noted by the online validators):
"Content":"\u003cbr\u003eMicrosoft Azure Storage provides many services...
Any ideas?

Why Using JSON in MVC application?

First i would like to apologize if this is a stupid question.
While learning MVC i came a cross creating a strong type views based on model which for example will display all Users by 2 different functions, first will return a View passing a collection of users second will return a collection of JSON objects. so my question is, as i'm not familiar with JSON and for me using Models are more clear, why then using JSON in MVC?
In short why using:
var users = _db.Users
.Where(r => r.Name.Contains(q))
.Take(10)
.Select(r => new { r.Name,r.LastName,r.Address.Country });
return Json(users, JsonRequestBehavior.AllowGet);
In place of:
var users= _db.Users
.Where(r => r.Name.Contains(q))
.Take(10);
return View(users);
Maybe this is a bad code example, but why converting Models to Jason before passing them to a view, if we can directly pass the models.
For the first code snippet, it is more likely that it is used for a ajax call to seamlessly load the data from the server to the client and perhaps keep refreshing it without reloading the page. Also, the Users entity may have much more information than needed by the client, so the first example is reducing the information served and doesn't require you to create a new model to represent it.
The second example would be a controller action actually returning a view and that view is strongly typed.
If you would make a project that uses the WebApi, you wouldn't return views, you would expect the client to ask for data and that the client renders it how it sees fit.
If you want the call to return HTML that can be rendered in a browser, you would return a View, which basically takes the data and applies it to an HTML template.
If you want the call to return data only (most likely to be processed by an AJAX request), then you would return JSON.
The first is going to return JSON with a content type of application/json while the latter will return html with the content type text/html (after the appropriate View Rendering Engine has rendered the view in question) - they can be considered two different representations of the same resource. You may want to return JSON in response to a request made via AJAX and return only the data from the model that is required, but you may want to return HTML in response to a "normal" request.
out of the box, ASP.NET MVC does not support Content Negotiation, that is, make a request with the Accept header set to a particular MIME type will likely not yield a response with the expected content type - controller actions will in the majority of cases be configured to return a resource in one particular content type (usually html). ASP.NET Web Api on the other hand does support Content Negotiation out of the box.
JSON (= data only) is generally used in asynchronous (AJAX) requests as they can easily be processed by Javascript, while Views are styled HTML responses ready to be displayed by the browser.
Client side libraries understand JSON very well, so if you want to parse the result and manipulate them using a client side framework/custom scripts, then JSON is a better option (AngularJs is one example).
In Addition to your question, when using JSON, first you convert Model to JSON but when you users post a request you might reconvert JSON to model in order to persist result to DB. :-)
I

pass value from apicontroller to view in asp.net mvc4

I have list of data in my api controller.
I want to pass this data to view using something similar to viewbag.
I know we cant use viewbag in apicontrller , So Is there any alternative for it.
Normally ApiControllers do not return views. They return models, or HttpResponseMessage for that matter. So you could simply have a view model that will contain the required property and then have your API action return this view model.
You are not supposed to tho that, the API controllers return only data (XML, Json, etc). So you should have two controllers:
System.Web.Http.ApiControlle Use this to return collections of data for example:
public List<Company> Get()
{
return this._companyService.GetCompanies();
}
Returns a list of companies in Json or XML not a view.
System.Web.Mvc.Controller use this one for returning HTML without data for example an HTML table without rows or client-side templates.
How to link the two? The idea is to render in the client-side with JavaScript, there is a good few reasons to do it this way, the main ones are that you have data and presentation in two completely separated feeds so you will be able to re-use your data feed (in mobile apps for example).
To render in the client-side is good idea to use some JavaScript rendering engine, take a look to http://handlebarsjs.com/.
Use Jquery.getJSON() to get your JSON and get your handlebars template from your DOM or via Ajax, select a DOM alement to insert the generated HTML. Once you have the JSON, template and container use the function below:
function RenderJson (json,template,container) {
var compiledTemplate = Handlebars.compile(template);
var html = compiledTemplate(json);
$(container).html(html); //set new content
}
I know it can seem like a more complicated process but it you try it you will see the advantages, you will be able for example to test your data feed and your data presentation separately.
Hope it helps :)

Best way to transfer data from view to javascript

I'm working in an Asp.Net MVC 3 project where in one of my javascript file, a message is displayed to the user. This message in currently in one language but I want this message to be in multiples languages. I don't want to store theses languages directly in the javascript file but instead in a database. I want to know if it possible to transfer data (string) from the view to the javascript file.
One solution that I've found is to set data from my view in hidden fields and then extract it from my javascript file. The problem with this solution is that I must put a lot of hidden fields and this is very hard to maintain.
Is there any other solution to this problem?
You can try JavaScriptModel ( http://jsm.codeplex.com ).
With this library you can add variables by calling the following function in your controller action:
this.AddJavaScriptVariable("VariableNameInJavaScript", SomeValue);
You can pass primitive types or complex types.
Furthermore you could execute javascript functions with the following code in your controller action:
this.AddJavaScriptFunction("FunctionInJavaScript", SomeParameter, AnotherParameter);
Yes, your on the right path. All you need to do is hydrate your model appropriately and use Razor syntax to pass the value from the server to the client "along the following lines":
<script src="#Url.Content("~/scripts/yourapi.js")"></script>
<script>
yourapi.foo('#Model.SomeValue');
</script>

Categories