MVC - JSON + HttpException - Return An Error Page

Jan 30, 2011

I'm trying to return an error page indicating that the user couldnt be found and therefore I throw a HttpException with status code 404, however for some reason it wont redirect to the error page? - Is there some sort of trick to handle error pages with JSON that I should be aware of? My current code:

public ActionResult Details(int id)
{
User userToGet = _session.Query(new GetUserById(id));
if(userToGet == null)
{
throw new HttpException(404, "User not found");
}
DetailsUserViewModel userToViewModel = AutoMapper.Mapper.Map<User, DetailsUserViewModel>(userToGet);
return Json(new
{
HTML = RenderPartialViewToString("Partials/Details", userToViewModel)
}, JsonRequestBehavior.AllowGet);
}

Update - Some more code:

// MyJs.js
function openBox(object) {
$("body").append("<div id='fadeBox'></div><div id='overlay' style='display:none;'></div>");
$("#fadeBox").html("<div style='position:absolute;top:0;right:0;margin-right:2px;margin-top:2px;'><a id='closeBox' href='#'>x</a></div>" + object["HTML"])
$("#fadeBox").fadeIn("slow");
$('#wrapper').attr('disabled', 'disabled');
$("#overlay").show();
jQuery.validator.unobtrusive.parse('#mybox') /* Enable client-side validation for partial view */
}
// List.cshtml
@model IEnumerable<MyDemon.ViewModels.ListUsersViewModel>
<table style="width:100%;">
<tr style="font-weight:bold;">
<td>UserId</td>
<td>UserName</td>
</tr>
@foreach (var user in Model)
{
<tr>
<td>@user.UserId</td>
<td>@user.UserName</td>
<td>@Ajax.ActionLink("Details", "details", "account", new { id = @user.UserId }, new AjaxOptions() { HttpMethod = "GET", OnSuccess = "openBox" })</td>
</tr>
}
</table>

View 1 Replies


Similar Messages:

MVC :: Return HttpException To Jquery Function On Ajax OnFailure Method

Apr 28, 2010

i am using ajax.beginform in my view i need to return a string if ajax request is faild.by this code return the string to view

[Code]....

how can i return the string to jquery function to show on OnFailure method and the function show a Partial View?

View 4 Replies

AJAX :: Return Json Format From Page's Webmethod?

Jun 7, 2010

I have the following web method , no success on return a correct Json format.

[Code]....

GetAll() return list of type "Company" POCO classes.

The web method complaint type "Company" could not cast to object. However I could not just return the Company type because client side Json only accept its 2 properties -"CompanyName", "ID" and I want to keep it that way.

Of cause, I had tried create a CompanyDTO which only have those two properties, but same error - "Unable to cast object of type..."

How should I modify in my web method to make it able to return a list of partial "Company" type in Json format?

View 4 Replies

System.Web.HttpException: Request Timed Out Error?

Nov 1, 2010

I have a thread class which makes a web request. After 20-30 urls request, its throwing exception: System.Web.HttpException: Request timed out. My code is below where it is throwing exception:

httpReq.AllowAutoRedirect = false;
httpReq.KeepAlive = false;
httpReq.Headers.Add("Location", "");
httpReq.Timeout = this.HttpRequestTimeout;
httpRes = (HttpWebResponse)httpReq.GetResponse();

In last line : httpRes = (HttpWebResponse)httpReq.GetResponse(); it is throwing exception. "The remote server returned an error: (403) Forbidden."

View 1 Replies

State Management :: Server Error: [HttpException (0x80004005): Invalid_Viewstate

Feb 8, 2011

This bug is very difficult to troubleshoot. I run 4 apps on the same server, all 4 are clones from the first one, just differ on their database connection. 2 run perfectly, but on two of them, when making a postback from a certain page, by clicking a button or by changing a datagrid page, it throws this error:

[code]....

View 1 Replies

MVC Return Json Result?

Feb 4, 2011

I have a controller that uploads a file. I would like to return a json result with bool success (if successfully uploaded otherwise false) and message (this could be error message that occured OR link to a file OR link to an image, depending on what was uploaded).What's the best way to approach thisI have this

public class UploadedFile
{
public bool Success { get; set; }
public string Message { get; set; }
}

then In my controller I would set Success to true/or/false and Message to <a href OR <img am i on the right track?How would i then parse this in the view so that when image it will show an image, if link show a link, if error simply alert error.

View 2 Replies

How To Get A Method To Return Json In C# And MVC 2 Or 3

Nov 16, 2010

i use JSon to return allot of results when building a website, but find myself writing a a lot of code like this:

[Code]....

and then simply call this function with whatever IEnumerable results i have my question is would i be on the right lines here, what would be the best possible way to do this as it makes no sense to be writing in MVC and OOP but to keep rewriting code to just FROM ?

View 5 Replies

How To Return JSON In A Webservice

May 27, 2010

[code]....

What's wrong?

Edit: And what if I need to return {Message:'',Type:1} ?

Edit2: The answer for the last one is: I can return a Dictionary<string, string>

View 2 Replies

Two Objects In Same Json Return?

Nov 16, 2010

I have Categoreis and Locations I would like return both in one method. How can make a use of both Categories.ToList() and Locations.ToList()? What type of object should I return?

View 1 Replies

Return Data As JSON

Mar 2, 2015

Code:
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static LoanSize[] GetLoanSize()

[Code] ....

This is how i read it in client size

Code:
function GetLoanSize() {
$.ajax({
type: "POST",
url: "Default.aspx/GetLoanSize",
data: "{}",
contentType: "application/json; charset=utf-8",

[Code] ....

My only problem is that it take too long to populate the dropdown. How to convert it into a JSON format so it will more faster populating the data.

View 11 Replies

How To Get Ajax.Net PageMethod To Return JSON

Jan 12, 2010

I am using an AJAX.Net to call an ASP.Net PageMethod, which returns JSON serialized JSON data

{"d":"[{"Fromaddress":"testfrom1@test.com","Toaddress":"testto1@test.com"},{"Fromaddress":"testfrom2@test.com","Toaddress":"testto2@test.com"}]"}

The Response Header states the content type as

"Content-Type application/json; charset=utf-8"

However, the data is just available as a string, and does not seem to be available as JSON data from javascript. What do I need to do to work with the returned data as JSON from javascript?

View 1 Replies

Accessing The Json Return Variable?

Feb 15, 2011

I have an ajax call handled with jquery like this:

[code]....

Nothing's being outputted. What am I missing?

View 1 Replies

MVC :: Json Does Not Return Date Properly?

Apr 5, 2010

Code like this....

[Code]....

View 4 Replies

MVC :: Join 2 SQL Tables Together And Return Them In A Json?

Aug 3, 2010

I am new to MVC and am trying to join 2 SQL tables together and return them in a Json. One table is OutreachProgram. The other table is UserInfo. I want to return the rows from the OutreachProgram table that match on CenterID with the UserInfo table.

The code that exists now will pull all rows from the OutreachProgram table. I can't figure out how to add the UserInfo table to the query to make it work.

JsonGrid <OutreachProgram> grid =
new
JsonGrid<OutreachProgram>(db.OutreachProgram,
new
OutreachProgramFilter());
public Array GetItems(IQueryable<OutreachProgram>
source)
{ return (from r
in source.AsEnumerable()
select
new {
ID = r.OutreachProgramID, CenterID = r.CenterID, DateOutreachProvided = r.DateOutreachProvided.ToShortDateString(),
NameOfProvider = r.NameofProvider.ToString(),
}).ToArray();
}

View 2 Replies

Return Data From An Asmx Into JSON?

Jun 15, 2010

I want to return an array of javascript objects from my asp.net asmx file. ie.

variable = [
{
*value1*: 'value1',[code]....

I seem have been having trouble reaching this. I'd put this into code but I've been hacking away at it so much it'd probably do more harm than good in having this answered. Basically I am using a web service to find names as people type the name. I'd use a regular text file or something but its a huge database that's always changing - and don't worry I've indexed the names so searching can be a little snappier - but I would really prefer to stick with this method and just figure out how to get usable JSON back to javascript. I've seen a few that sort of attempt to describe how one would approach this but I honestly think microsofts articles are damn near unreadable.

EDIT: I'm using the $.ajax() function from jQuery - I've had it working but it seems like I was doing it in bad practice not returning and using actual JSON. Previously I'd take a string back and insert it into html to use the variable it set - very roundabout.

View 1 Replies

Runtime HttpException Affecting Only One Page / Usercontrol?

May 26, 2010

We're having an issue with a .NET 3.5 WebForms site where occasionally our error logs start filling up with the following error message:

"Multiple controls with the same ID 'ctl09' were found. FindControl requires that controls have unique IDs."

I know very little about the exception as I have never seen it while debugging locally and have never caught it in the error logs soon enough to run a remote debugging session. I do know that an application pool recycle fixes the issue.

This only affects a single [high traffic] page in the site. The strange thing is that the site uses the pre-4.0 ID generation logic. So, when the page is working, there isn't an html element in the entire view source that isn't some autogenerated control ID prefix followed by a the 'actual' IDs (i.e. ctl09_someID_someOtherID).

What would case a control to randomly stop being built correctly? Other than the Global.asax, how can I trap this error and force the control to ... recompile? App pool to recycle?

View 1 Replies

Soapui Mocking Services Which Return Json

May 24, 2010

Microsoft Ajax can expose webservices which respond with json or xml depending on configuration. I would like to mock these services using soap ui. Using the wsdl I can do this to mock the services in the case where xml is returned, however how can I mock the response when JSON is returned?

View 1 Replies

Return A Partial View In JSON From A Controller In MVC?

Mar 16, 2011

I have a list of items(surveys) displayed on my home page. When I click the edit button for a particular item I have a modal pop up with the items details to edit. When the user clicks Save I submit the form via ajax. Depending on whether ModelState.IsValid == true I want to update the modal with validation information or close the modal and update the list of items with the new information.

This is how I am submitting the form:

[Code]...

My Questions

The only thing I can think to do is return JSON from my controller with a flag indicating the state of the ModelState.IsValid and the corresponding partial that I should show.

1) How would I do this?

2) Is there a better way?

Update

I found this: [URL]

but it seems more likely that I am going about the whole thing incorrectly.

View 3 Replies

WebMethod Return Values In JSON Format?

Jan 24, 2010

How to return values from Webmethod to the client in JSON format? There are two static int values that i want to return.Do I need to create new object with those 2 properties and return it?The GetStatus() method is called frequently and i don't like the idea of creating a special object each time just for json formatting...

[WebMethod]
public static int GetStatus()
{
int statusProcess,statusProcessTotal;
Status.Lock.EnterReadLock();
statusProcess=Status.Process; //Static field
statusProcessTotal=Status.ProcessTotal; //Static field
Status.Lock.ExitReadLock();
return ...
}
On client side I catch the return value in :
function OnSucceeded(result, userContext, methodName)
(PageMethods.GetStatus(OnSucceeded, OnFailed);)

View 1 Replies

WCF / ASMX :: Return JSON Data From A 2.0 Web Service?

Sep 10, 2010

Just ramping up on JSON and JQuery and returning data to a ASP.NET web page from a web service using Ajax. The JQuery part is pretty straight-forward. However, when trying to return JSON formatted data instead of XML from a 2.0 web service, I'm stuck. The web service does have the System.Web.Script.Services.ScriptService attribute, so I can hit it via JavaScript; however, the web service always...always...returns data in XML format, no matter if I explicitly say I want JSON as the datatype in my JQuery code. So I don't know if this is an issue with the web service or the JQuery code. I posted this here, but realize that the category could be incorrect depending on where the issue is. Is there no way to return JSON data from a 2.0 web service? It's a production web service, so I can't change the code unfortunately.

View 3 Replies

Return A Json Object In Webforms Programming?

Jun 2, 2010

In ASP.Net MVC action methods can return json objects simply by returning something like so:

JSon([whatever])

How do I return a JSon representation of say List<String> with webforms either through a service or through a method in the code behind of an aspx page? This seems incredibly confusing compared to ASP.Net MVC.

View 3 Replies

MVC Return To Page On Error With Fields Populated?

Jan 13, 2011

I am starting a new project in Asp.net MVC 2.I have been mostly a webforms developer and have limited exposure to Asp.Net MVC and hence this is probably a noob question.

My situation is as follows:

I have a create page for saving some data to the DB. The view for this page is not strongly bound / typed - so the way I am extracting the data from the view is by looking at the POST parameters.

Incase there is an error (data validation, etc), I need to send the user back to the previous page with everything filled in the way it was and displaying the message.

[Code].....

View 1 Replies

Read An External JSON File Using Json.NET On Page Load?

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

AJAX :: Return Complex Type In Json Format?

Jun 11, 2010

I was using Extjs to send a json object to my asp.net webservice/Update method , but I find the following error in firebug reseponse.

[Code]....

View 1 Replies

Jquery - How To Return Json Causes Save File Dialog In Mvc

May 26, 2010

I'm integrating jquery fullcalendar into my application.
Here is the code i'm using:

in index.aspx:

[Code].....

View 5 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved