admin管理员组文章数量:1389754
I'm building a webapp using ASP C#.NET MVC3.
I have a View (.cshtml file). In this View I have a javascript function "SomeFunction()" which calls a .NET function through Razor like so: "@Html.Raw(Json.Encode(Model))". So everything put together it looks like:
SomeFunction(){
var sections = @Html.Raw(Json.Encode(Model));
}
Note the @ please.
This function throws an exception (this exception to be exact: Increase json response maxJsonLength in MVC 4) when the size of the string exceeds the maximum (too many sections basically). Well the requirements of my website don't instruct me to actually deal with this (luckily) by retrieving the data in pieces async and whatnot. I'm fortunate enough to simply catch this exception and tell the user: "Too many sections! Please define a larger size for sections." Or something like this. Alas I don't really understand how to do this exactly. I've tried the following:
SomeFunction(){
try {
var sections = @{try {
Html.Raw(Json.Encode(Model));
} catch (Exception e) {
throw new Exception("Exception caught in .NET");
}}
} catch(err) {
alert('.NET exception caught in Javascript!');
}
}
Note the @ infront of the 'try' to denote Razor syntax.
The 'alert' in the catch clause in javascript is never reached. I e from desktop dev so I'm still a web novice. How is this normally done?
Thanks a lot in advance for helping me.
I'm building a webapp using ASP C#.NET MVC3.
I have a View (.cshtml file). In this View I have a javascript function "SomeFunction()" which calls a .NET function through Razor like so: "@Html.Raw(Json.Encode(Model))". So everything put together it looks like:
SomeFunction(){
var sections = @Html.Raw(Json.Encode(Model));
}
Note the @ please.
This function throws an exception (this exception to be exact: Increase json response maxJsonLength in MVC 4) when the size of the string exceeds the maximum (too many sections basically). Well the requirements of my website don't instruct me to actually deal with this (luckily) by retrieving the data in pieces async and whatnot. I'm fortunate enough to simply catch this exception and tell the user: "Too many sections! Please define a larger size for sections." Or something like this. Alas I don't really understand how to do this exactly. I've tried the following:
SomeFunction(){
try {
var sections = @{try {
Html.Raw(Json.Encode(Model));
} catch (Exception e) {
throw new Exception("Exception caught in .NET");
}}
} catch(err) {
alert('.NET exception caught in Javascript!');
}
}
Note the @ infront of the 'try' to denote Razor syntax.
The 'alert' in the catch clause in javascript is never reached. I e from desktop dev so I'm still a web novice. How is this normally done?
Thanks a lot in advance for helping me.
Share Improve this question edited May 23, 2017 at 11:50 CommunityBot 11 silver badge asked Oct 31, 2013 at 10:29 Danny van der KraanDanny van der Kraan 5,3766 gold badges34 silver badges42 bronze badges 2-
In don't understand how is it working? Is it within a
cshtml
file which will be render via Razor? If so How does it e with Javascript!? Can you put more details of your situation? – mehrandvd Commented Oct 31, 2013 at 10:35 - I'll answer your proposed answer. – Danny van der Kraan Commented Oct 31, 2013 at 19:29
5 Answers
Reset to default 4Technically, you can't.
Because these are two separate languages running in separate environments (one on the server, the other on the client) the best thing to do is to catch the exception within the ASP.NET application and then return the exception to the client side formatted as a string along with some indication as to whether the execution was successful or not.
As simple example would be this ajax request/response:
Our custom response object:
public class JsonResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
Usage:
[HttpPost]
public JsonResult DeleteMember(int id)
{
try {
this.memberService.DeleteMember(id);
}
catch (Exception ex)
{
return Json(new JsonResponse { Success = false, Message = ex.ToString());
}
return Json(new JsonResponse { Success = true });
}
Then your client side Javascript would have the object returned to it, where you'll be able to see if the request was successful, and if not then what the exception/error message was.
<script type="text/javascript">
$(function() {
$.post('@Html.Action("Member", "DeleteMember")', function(response) {
if (response.Success == false) {
alert(response.Message);
} else {
alert("Member was deleted!");
}
});
});
</script>
you are mixing two things here. The Javascript is executed on client side and the c# code resides and throws exceptions on the server side.
so what basically is happening here is that when this view is being rendered. this code is executed
@try{
Html.Raw(Json.Encode(Model));
} catch (Exception e) {
throw new Exception("Exception caught in .NET");
}
} catch(err) {
alert('.NET exception caught in Javascript!');
}
and finally what is send to client is the output of Html.Raw(Json.Encode(Model))
which in turn generated nothing. as you have not included the @
prefix.
Instead what you can do is check the length of the string on the client side itself
SomeFunction(){
var sections = "@Html.Raw(Json.Encode(Model))";
if(sections.length > [MAX LENGTH]){alert(SOMETHING);}
else{
sections = JSON.parse(sections);
//your old code here
}
}
If you're creating your javascript function via Razor(which sounds some kind of strange!) you should decide how to manage the exception, server side or client side. The code below is an exception management which will occur at the server side which I think suits for you:
SomeFunction(){
string sections;
@try {
sections = Html.Raw(Json.Encode(Model));
}
catch (Exception e) {
sections = "Error";
}
if (sections == "Error")
{
alert("Your message");
}
}
you may try this
SomeFunction(){
var sections = @{try {
Html.Raw(Json.Encode(Model));
} catch (Exception e) {
Html.Raw(false)
}}
if(!!sections){
alert('.NET exception caught in Javascript!');
}
}
Big Joe, Parv Sharma and mehrandvd all have a point. I realize that now. Thanks again for contributing. And I'm sorry I didn't immediatly understood your answers.
However none was exactly usefull in my situation. Atleast... I tried Big Joe's and couldn't get it to work like i wanted to (because a Post leads to reloading the page which I didn't need).
What I did was:
In the Action of the Controller where my Model (a collection of Sections) is filled I already try now to serialize the collection to Json (so that is server side). This looks like:
List<Models.Section> sections = Models.Section.GetSectionsByCampaignID(campaignID);
try {
string sectionsAsJson = System.Web.Helpers.Json.Encode(sections);
} catch (Exception) {
sections = null;
}
Now all I had to do in the javascript in the View is checking for null, like so:
var sections = @Html.Raw(Json.Encode(Model));
if(sections != null){
//Some code to do stuff with the sections.
} else {
alert('Sorry for the inconvenience, but there are too much sections to draw. This is causing a technical error. Please edit the map and define a bigger section size.');
}
So yeah, maybe not how experienced web developers would solve it. But it works for me. Does any experienced web developer foresee any major issues with this? Please ment. I'm always ready to learn more.
本文标签: aspnet mvc 3How to catch a NET exception in javascriptStack Overflow
版权声明:本文标题:asp.net mvc 3 - How to catch a .NET exception in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744711273a2621143.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论