MVC :: Returning A Function In JSON?
May 26, 2010
I 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.
View 6 Replies
Similar Messages:
Aug 2, 2010
I want to return pure JSON from an MVC 2 Action. How can i do this?
View 4 Replies
Sep 20, 2010
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?
View 1 Replies
Apr 13, 2010
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.
View 2 Replies
Nov 25, 2010
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);}
View 6 Replies
Nov 29, 2010
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]....
View 4 Replies
Nov 27, 2010
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 ?
View 6 Replies
Mar 8, 2011
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();
}................
View 1 Replies
Aug 25, 2010
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.
View 1 Replies
Jan 5, 2010
I have a call to a function in my business logic area. It should be returning a true.
[URL]
This url above is the culprit. The code doesn't seem to like the .asp type of file. I wonder why this is the case. I get a true response for a html or php type of file. The above returns false. Does anyone know why?
[Code]....
[Code]....
Public
Shared
Function MakeURL(ByVal url
As
String)
As
String
Return
"http://" & url.Replace("http://",
"")
End
Function
View 1 Replies
Jun 10, 2010
This is regarding GetPreloadedEntityBody() function of HttpWorkerRequest class . I am using this method to get perloaded data of requested page. but GetPreloadedEntityBody() function alway returns me null value , while same code is working for server with IIS6.0
1) I have Application_PostAcquireRequestState event . on which i do all user releated validation.
2) After Sucessful validation i am creating object like below code snippet of worker process.
Dim hwr As HttpWorkerRequest =
CType(context.GetType.GetProperty("WorkerRequest", Reflection.BindingFlags.Instance
Or Reflection.BindingFlags.NonPublic).GetValue(context,
Nothing), HttpWorkerRequest)
3) AFter That checking where request has body or not and the calling GetPreloadedEntityBody() which is returning null alway for IIS7.0 ,while in IIS6.0 same code is working fine.
if hwr.HasEntityBody
Then
Dim preloadedBufferData
As Byte() = hwr.GetPreloadedEntityBody()
end if
what more do i have to do so that i can get return value form GetPreloadedEntityBody() function.
View 2 Replies
Apr 19, 2010
I have a web service in ASP.NET being called by a time-sensitive process. If the web service takes longer than N seconds to run I want to return from the call so the time sensitive operation can continue. Is this possible and if so what is the code for this?
View 2 Replies
Feb 22, 2011
i have made a simple chat class but for displaying the msg i use a textbox but by ajax and page post back the scroll bar moves up and its very unprofessional so i need a way to set my returning function string to be displayed in div with scroll bar
View 3 Replies
Jan 31, 2011
How can I get the result of a method that return a JsonResult and cast into string.
[HttpPost]
public JsonResult AnalyseNbPayment(DateTime dt, DateTime dt2,int FrequencyID) {
if (FrequencyID == ApplConfig.Frequency.WEEKLY) {
return Json(new { val = GetNbWeek(dt, dt2) });
}
else if (FrequencyID == ApplConfig.Frequency.MONTHLY) {
return Json(new { val =GetDateDiffInMonth(dt, dt2) });
}
else if (FrequencyID == ApplConfig.Frequency.QUARTELY) {
return Json(new { val = GetQuarterLy(dt, dt2) });
}
else if (FrequencyID == ApplConfig.Frequency.BI_MONTLY) {
return Json(new { val = GetBiMontlhy(dt, dt2) });
}
else if(FrequencyID == ApplConfig.Frequency.YEARLY)
{
return Json(new { val = GetNbYear(dt, dt2) });
}
return Json(new { val =0 });
}
I want to call my method like this
string MyValue = AnalyseNbPayment(Convert.ToDateTime(ViewModel.oRent.DateFrom), Convert.ToDateTime(ViewModel.oRent.DateTo), Convert.ToInt32(oLease.FrequencyID)).val.ToString(); <br />
View 1 Replies
Apr 20, 2010
I have a json object collection of geo locations that I build in the server. Each of those objects has two properties: "marker" and "onClick". Marker is for storing a Google Maps marker object and the onClick stores the name of the function to be called when that marker is clicked on the map.When I'm pushing the location objects into an array using javascript in the client side, I create the markers and assign them to each location object within the array.
My problem is that when I bind the marker with the onClick property, the function won't be found in the DOM and get an error.Is there a way to declare a property in a json object for using it on an event binding?
View 1 Replies
Feb 9, 2011
I have a dropdown box on my aspx page, I would want o pupulate it using jquery's json of calling a method. I do not want to call a webservice method. I have a class, in C# and want to call a method from the class.
View 6 Replies
Jan 26, 2010
I have problem with a stored procedure and function that return the same shape, but as they are different methods LINQ won' t let me cast between the two. Please see code for the two SPROCs below (This is actually simplified to represent the problem, so please don't spend lots of time explaining alternative ways of writing the function/sproc.)
Table Valued Function
"getCategories()"
SELECT categoryName, categoryID FROM categories
SPROC "getUnusedCategories"
SELECT categoryName, categoryID FROM CategoryInstances cI
FROM dbo.SMAN_getCategories(@SiteMANID, @SectionID) c
LEFT JOIN @EntityResultsTable er
View 2 Replies
Jun 4, 2010
I'm trying to create a JSON object on client-side and pass to a server-side function. Then instantiate it on server-side using JSON string representation.
So I create jSON object on client-side
var myJsonObject = {
"arg1": var1,
"arg2": var2
}
and pass it in to
WebForm_DoCallback(controlID, myJsonObject , null, null, null, true);
When I try to retrieve this JSON object on server-size I get as a string representation of JSON [object Object]
So in following server-side function, the argument value is [object Object]
public void RaiseCallbackEvent(string jsonObj)
I was expecting a string representation of JSON object. How do I pass in a string representation?
View 1 Replies
Aug 22, 2010
have this site that has an api that can provide city name if I send my zip code as a parameter. http://www.postnummersok.se/api?q=16447the result is returned as a json object. Now i just want to read the result in my js function.I have tried the following but it always returns null:
function postnr() {
View 9 Replies
Aug 11, 2010
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": "??" } } }
View 1 Replies
Jul 18, 2010
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
View 5 Replies
Dec 29, 2010
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.
View 4 Replies
Feb 1, 2010
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]....
View 1 Replies
Jan 21, 2011
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
Apr 4, 2011
In my javascript code I am getting json string from cs file
var tmpString="<%=resultset2%>";
In cs I am concatenating strings to build json string. Here is an issue the json string is returned as a string and it has " with it.
"[{id:'1',name:'Aik'},{id:'2',name:'Aik or Aik'}]"
Because of " in beginning and end javascript code treat it as a string.
View 2 Replies