MVC :: Returning Pure Json From An App?
Aug 2, 2010I want to return pure JSON from an MVC 2 Action. How can i do this?
View 4 RepliesI want to return pure JSON from an MVC 2 Action. How can i do this?
View 4 RepliesI would like to return an function in some JSON. How can I stop my function being output as text (how can i stop it being wrapped in quotation marks?).
eg: [Code]....
In script the value of name is just a string. Is there some object I can set name to that will wrap my script and emit as script not a string?I want to do this to better control the "remote" rule of jQuery validate. I have my own dataannotationmodelvalidator for it and its doing this atm:
[Code]....
Which is working fine for the most part except I can't get the value of 'name' to be a function. It comes out as a string. Alternatively is there someway to control what JSON serializer this thing is using alternatively. We need a wrapper function so you can do something like:
name = Emit("function(){ return $(this).val(); }")
and have it come out as script not a string.
I had my ASP.NET MVC actions written like this:
//
// GET: /TaxStatements/CalculateTax/{prettyId}
public ActionResult CalculateTax(int prettyId)
{
if (prettyId == 0)
return Json(true, JsonRequestBehavior.AllowGet);
TaxStatement selected = _repository.Load(prettyId);
return Json(selected.calculateTax, JsonRequestBehavior.AllowGet); // calculateTax is of type bool
}
I had problems with this because when using it in jquery functions I had all sorts of error, mostly toLowerCase() function failing.
So I had to change the actions in a way that they return bool as string (calling ToString() on bool values), so that thay return "true" or "false" (in the qoutes) but I kinda don't like.
How others handle such a case?
What i would like to accomplish is that a partiel view contains a form. This form is posted using JQuery $.post. After a successfull post javascript picks up the result and uses JQuery's html() method to fill a container with the result.
However now I don't want to return the Partial View, but a JSON object containing that partial view and some other object (Success -> bool in this case).
I tried it with the following code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, Item item)
{
if (ModelState.IsValid)
{
try
{
[Code].....
However I don't get the HTML in this JSON object and can't use html() to show the result. I tried using this method to render the partial as Html and send that. However this fails on the RenderControl(tw) method with a: The method or operation is not implemented.
This is probably something simple. The following JQuery call is executing and calling the controller. The controller is executing correctly. I used the sample data that's commented out to verify that the templates were working also. However, the success function is not executing in the browser. Any thoughts or other ways I can debug this?
<script type="text/javascript">$(document).ready( function(){ alert("Here"); @* var myData = [ {first: "Jane", last: "Doe"}, {first: "John", last: "Doe"} ]; *@ $.getJSON( "/User/Filter",function(myData){ $("#myDataTemplate").tmpl(myData).appendTo("#itemContainer"); } ); alert("there"); }
);</script>
//Controller
public ActionResult Filter() { var myData = this.repository.GetAllUsers(); //return Json(myData); return Json(myData, JsonRequestBehavior.AllowGet);}
I have been trying for two months to get this code working, and I am close, but still confused. I want the JQuery UI Autocomplete function to call an web service which returns JSON data and display that data for selection, and on selection put the selected value into a hidden field.
There are several issues:
1) The autocomplete function is not firing
2) The source: "/AutoSuggest.asmx/DOTFind?" line throws an invalid object exception
3) The service requires two parameters: (string prefixText, int count) - count tells it how many records to return.
4) I am not at all certain that this code will accept JSON data that comes back from the service
Here is the code:
[code]....
My Problem is that i am returning a json string from a webmethod from an aspx page.
I want to create a dynamic html table using that json string but found no solution for that.
Can anyone Provide me the solution to generate html table from json string ?
public class JsonBuilder
{
private StringBuilder json;
public JsonBuilder()
{
json = new StringBuilder();
}
public JsonBuilder AddObjectType(string className)
{
json.Append(""" + className + "": {");
return this;
}
public JsonBuilder Add(string key, string val)
{
json.AppendFormat(""{0}":"{1}",", key, val);
return this;
}
public JsonBuilder Add(string key, int val)
{
json.AppendFormat(""{0}":{1},", key, val);
return this;
}
public string Serialize()
{
return json.ToString().TrimEnd(new char[] { ',' }) + "}";
}
}
Here is the Web Method [WebMethod]
public static string GetPersonInfo(string pFirstName, string pLastName)
{
var json = new JsonBuilder().AddObjectType("Person");
json.Add("FirstName", "Psuedo" + pFirstName).Add("LastName", "Tally-" + pLastName);
json.Add("Address", "5035 Macleay Rd SE").Add("City", "Salem");
json.Add("State", "Oregon").Add("ZipCode", "97317").Add("Age", 99);
return json.Serialize();
}................
I Need by service contract to return the xml/json result depending on the request type. function which will convert my result set (i am using linq to sql) so that i do not need to create the xml format for the result set by iterating through the table row many times.What is the suitable way to do that.
I need a kind of short cut method which will convert the table data to xml result.Had i been using asp.net mvc i would have been able to generate the xml data by overriding the the ExecuteResult method in the ActionResult and giving Conetnt-Type = "text/xml" as OP.But since i am using Wcf i don't have the controller context(as controller context is the parameter that needs to be passed to Execute Result).
My present code for converting the table data to the xml format is below.
public XDocument UsersLists(string authToken)
{
bool IsAuthenticated = Authenticate(authToken);
XDocument xDoc = new XDocument();
XElement root = new XElement("Users");
[Code]....
I need to eliminate this way of generating xml for each table records.
I try to use the jquery + json to get all elements in form and build a JSON var to post in a ASP.NET MVC method.
[Code]....
It method get all fields in a form and build a JSON, but it dont put JSON inside JSON.
Example:
If i have the follow form:
<input name="person.name"><input name="person.age"><input name="person.address.street">
The serialized string build a JSON like this
{ "person.name": "??", "person.age": "??", "person.address.street": "??" }
I need a plugin or some function to generate like this:
{ "person": { "name" : "??", "age" : "??", "address":{ "street": "??" } } }
We have a web project that contain its business methods in a class library project called "Bll.dll"
some methods of Bll.dll return List<> ... from a source - that i don't remember now - told that returning Collection<> is better than returning List<> Is it a valid ? Note that i don't make any process on values returned from BLL methods .. just view it in a web page
I want to alternate rowcolor in a GridView, using pure CSS, ie: I don't want to use asp.net themes; I'd rather not have to use jQuery, or define define AlternatingRowStyle-BackColor on each gridview (unless there's a reason I must). Here's my CSS (that isn't working):
.gridView {font-size:11px
}
.gridView tr:nth-child(even) {background-color: #FFF}
.gridView tr:nth-child(odd) {background-color: #FFCC00}
.gridView tr:nth-child(even) td {background-color: #FFF}
.gridView tr:nth-child(odd) td {background-color: #FFCC00}
(I included the .gridView {font-size:11px} just to confirm I am using the proper CssClass.) Is this not possible, or am I doing something wrong.
give a link with sample if possible
View 4 RepliesI want an asmx webservice with a method GetPeople() that returns the following XML (NOT a SOAP response):
<People>
<Person>
<FirstName>Sara</FirstName>
<LastName>Smith</LastName>
</Person>
<Person>
<FirstName>Bill</FirstName>
<LastName>Wilson</LastName>
</Person>
</People>
[Code]....
i need to call pure JS inside UpdatePanel becouse of DayPilotPro but when i am using UpdatePanel this is not possible. How can i call it?
I have what should be a relatively simple task that's frankly got me stumped. I've researched it until my brain is fried, and now I'm puntingHere's the scenario:I have an ASPX page (Q2.aspx) that is decorated with the WebService,WebServiceBinding, and ScriptService attributes. That page contains a method, GetAllContacts, that is decorated with the WebMethodattribute and returns a string containing JSON data. (For what it's worth, the pageitself contains no other controls or functionality.)I have an HTML page that contains JavaScript which uses the XmlHttpRequestobject to invoke the GetAllContacts WebMethod on the ASPX page and transformthe JSON data into an HTML table. I have verified that my Web.Config file contains the appropriate protocol handlersfor HttpGet and HttpPut in the WebServices section under System.Web.webServices.
I have verified that my Web.Config file contains the ScriptModule entry under theSystem.webServer.modules section, and that it matches the appropriate documentation.
However, when I view the HTML page in a browser, the following occur:The web request goes through, but the results are for the unprocessed HTML from the ASPX page.The GetAllContacts method is never invoked, as evidenced by setting a breakpoint in its code.The code to invoke the Web service, however, is invoked, and the JavaScript callbackfunction that is invoked upon request completion is properly invoked.
It appears that the JavaScript code is largely set up correctly, but for some reason that is completely escaping me at this point, the HTML page will simply not execute the WebMethod on the ASPX page, and simply returns the page as though it were a plain HTML GET request. Clearly, an HTML document can't be evaluated by JavaScript's eval function, which brings me to my problem. (Also note that the JSON data appears nowhere in the HTML that's returned.)I am, frankly, baffled. I've looked at dozens of Microsoft articles, StackOverflow posts, CodeProject articles, and who knows what else. My code looks like it's okay. But I know better. I'm missing something simple, stupid, and obvious. I just need someone to point it out to me.Below you'll find the ASPX page code and the HTML code, in the hope that they'll shed some light.ASPX Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
<body>
[code]...
I'm attempting to create a pure t-sql representation of the default SHA-1 password hashing in the ASP.Net Membership system. Ideally, what I would get would be this:
UserName Password GeneratedPassword
cbehrens 34098kw4D+FKJ== 34098kw4D+FKJ==
Note: that's bogus base-64 text there. I've got base64_encode and decode functions that round-trip correctly. Here's my attempt, which doesn't work: SELECT UserName, Password, dbo.base64_encode(HASHBYTES('SHA1', dbo.base64_decode(PasswordSalt) + 'test')) As TestPassword FROM aspnet_Users U JOIN aspnet_membership M ON U.UserID = M.UserID
I've tried a number of variations on the theme, to no avail. I need to do this in pure T-Sql; involving a console app or something like that will double the work. So if anyone can supply what precisely the syntax should be to duplicate that password from the ASP.Net membership stuff
In your opinion, what's the best way to create the server side to a pure Javascript application with ASP.NET? WCF rendering JSON? IHttpHandler? Update Like GMail, that runs in the browser (with a lot of Javascript) and submit and receive data with Ajax, for example.
View 2 RepliesAnalysis and design C# application with pure object orineted feature .
for example
I get all the requirement for the user, How to analysis the system , keeping future changes in mind , design and system with pure object oriented feature .
in Short : design system with pure object oriented feature so that it flexible so that in future new version can be launch easily
I am trying to use jQuery .load() to get straight html from a asmx web service:
$('#target').load('MyService.asmx/GetHtml');
In .NET code, GetHtml() returns as string:
[WebMethod(EnableSession = false)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Xml)]
public string GetHtml()
{
return "<span>Hi</span>";
}
That returns:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/"><span>Hi</span></string>
Notice that the string is encoded. With that encoding, $.load doesn't work right. The displayed text actually has the tags shown.
How can I get the WebMethod call to return just this?
<span>Hi</span>
I am Importing an excel file using oledb connection in asp.net.
but it is not working on server.
now i want to read excel file without interop.
How can i do it.
i have two buttons, which point to some onclick-methods in my code-behind file. inside these btn_click-codes i want to start adding pure html-code to my page, which was told to me in this forum having done by using ascx-files. note: there would be no code-behind in case of using the ascx-files.
however i do not see a possibility to load these ascx-files within btn_click-code? how to do?
in order to give you an idea of my html-code i have pasted two of them here:
[Code]....
maybe this is the complete wrong approach (as i.e. i believe that body-tags should not be included in .ascx-code). in this - how to do better?
I have a text file named gisQuery129.json that is created using Json.NET - [URL] There is an example on how to create a JSON file and I have done that successfully, but I want to read the file on a page load event and add the values to .NET textbox controls for input values in a query. The created file looks like the following:
{
"myData": {
"randomNumber": "129",
"Application": "MyMapApp",
"FeatureId": "ALL",
"Feature": "ALL",
"spatialQuery": "FEATURE_ID= '11111' AND REQ_SEQ_NUM= 1 AND RAND_PARAM= 129 OR FEATURE_ID= '22222' AND REQ_SEQ_NUM= 2 AND RAND_PARAM= 129"
}
}
I want to read the data in the above sample JSON data and then populate my textboxes something like this:
txtRandParam.text = "129"
txtApplication.text = "MyMapApp" and three more text boxes after that.
I want to retreive the data from database and assign it to dropdownlist. For that I'm using the following jquery in the onclick event
[Code]....
I use the JavaScriptSerializer class of ASP.net to serialize my object and return it to the client side. How can I deserialize the string using JavaScript?
View 4 Replies