In previous series of ASP.NET Tips and Tricks we learned basic configuration for ASP.Net applications and exception handling. You can also visit Part 1 and Part 2. In this article we learn new tips that are useful for both web forms and ASP.Net MVC applications.
Description
- When we are using the Response.Redirect method inside a Try Catch block a ThreadAbortException occurs.
Solution 1
- Response.Redirect(“redirectUrl”,false);
This method ends the current execution of the request and the error is prevented.
Solution 2
The second way to prevent a ThreadAbortException error is to handle the error in a try catch block.
- try {
- Response.Redirect(“redirectToSomeUrl”);
- }
- catch(ThreadAbortException e) {
- }
- The server cannot set the status after HTTP headers have been sent.
Solution: This error occurs for a number of reasons in ASP.Net MVC applications
When we export to Excel or any other format of export this type of error occurs. To prevent this type of error use the return type new EmptyResult() for ActionResult.
- Various types of ActionResult in ASP.Net MVC.
Answer:
ViewResult: Renders a view as a HTML page.
PartialViewResult: This is a reusable component. It renders a small person of the view in the page.
RedirectResult: Redirect to another action method.
RedirectToRouteResult: Redirect to another action method. A route parameter is required, for example Action Name and Controller Name.
ContentResult: Returns user-defined content types.
JsonResult: Returns a serialize JSON object.
JavaScriptResult: Returns a script that can be executed to the client.
FileResult: Returns a binary output to write to the response.
EmptyResult: Returns a null result.
- What is the difference between a string.Empty and “”?
Answer: string.Empty is a runtime constant. Its value is evaluated at runtime.
We cannot pass a string.Empty as the default argument in any method as the parameter because a default parameter in methods require a compile-time constant.
- public static void SomeMethod(string p1=string.Empty)
- {
-
- }
This method does not compile successfully:
- public static void SomeMethod(string p1=””)
- {
-
- }
Compilation failed because string.Empty is a runtime constant.
- Unfamiliar behavior of string.Trim() function
Solution: When we use the trim function for a null value a NullRefrence Exception occurs so the best way to prevent this error is to always check for a null and then use the Trim function.
To check the online behavior of the Trim function visit IdeOne.
- public static void Main()
- {
-
- string s1=null;
- string s2=string.Empty;
-
- Console.WriteLine(s2.Trim());
- Console.WriteLine(s2.Trim().Length);
-
-
-
Conclusion
In this article we learned the basis tips and tricks for ASP.NET MVC and common errors.