Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, December 23, 2014

[Resolved] WEBAPI ERROR using Json: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

hi lets see  how to resolve below error occurred while accessing web api for Json datatype :


 The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.



Solution:

go to global.asax file and in Application_Start() event add this below line.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 


After this u shud b able to run the webapi

Output:




Friday, December 5, 2014

Exception Handling in asp.net mvc using global.asax application_error() Method

hi now lets see how to catch exception in asp.net mvc using global.asax application_error() Method.

1. set Custom Error to Off in the web.config file
2. go to global.asax file and add this below code.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
string action;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = “HttpError404″; // create action method named HttpError404  in controller and also add the appropriate view
break;
case 500:
// server error
action = “HttpError500″; // create action method named HttpError500 in controller and also add the appropriate view
break;
default:
action = “HttpOtherErrors”; // create action method named HttpOtherErrors in controller and also add the appropriate view
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format(“~/ErrorHandle/{0}/?message={1}”, action, exception.Message)); // ErrorHandle is the controller Name 
}
else
{
Response.Redirect(String.Format(“~/ErrorHandle/{0}/?message={1}”, “HttpOtherErrors”, exception.Message));
}
}
3. in controller catch the exception message and show it in the view
public ActionResult HttpOtherErrors(string message)
{
ViewBag.ExceptionMessg = message;
return View();
}

[Resolved] Asp.net MVC Error : The controller for path ‘/favicon.ico’ was not found or does not implement IController

hi just came across this below error while debugging a asp.net mvc application.
 The controller for path ‘/favicon.ico’ was not found or does not implement IController
1
. 1. To resolve this go to RouteConfig.cs and write
 routes.IgnoreRoute(“{*favicon}”, new { favicon = @”(.*/)?favicon.ico(/.*)?” });
2
2. Now run the application and check.

using renderSection() , renderBody() and renderpage() in asp.net mvc Layouts || Masterpages in asp.net mvc

hi in this post i will show how to use renderSection() , renderBody() and renderpage() in asp.net mvc

create a empty mvc application.
1. In view folder create a Shared folder and add a new view called _Layout.cshtml. this view will act as a master page for all the pages.
1


4
in the above code i have used renderbody() which will write the contents from the other view.
for rendersection() we need to define section named RSection in the other view

2. now lets use _Layout.cshtml into our actual view named homePage.cshtml
to achieve this we need to write this below code
@{
Layout = “~/Views/Shared/_Layout.cshtml”;
}
2
in above code i have defined content for section RSection and also used renderPage() which will render view from other page named testPage.cshtml.
text hi im from homePage.cshtml will get called by renderBody() of the _Layout.cshtml.
Output:
3

Implementing bundling in asp.net mvc application || optimization of asp.net mvc application

hi here we will see how to implement bundling in asp.net mvc 4.
Bundling helps us to reduce the number of http requests made for calling .css and .js files. Bundling is a process where we bind multiple js or css files into one , so that we can reduce the number of http requests made for calling this files and thus improving the performance of a web application.

1. create a new mvc project, and go to manage nuget packages options and install asp.net web optimization framework.
11

2. now go to solution explorer app_start folder and create a new class called BundleConfig.cs
55

3. in bundleConfig.cs create seperate bundles for js and css files.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new Bundle(“~/bundles/mycss”).Include(“~/css/StyleSheet1.css”,”~/css/StyleSheet2.css”));
bundles.Add(new ScriptBundle(“~/bundles/jsbundle”)
.Include(“~/js/jquery-2.1.1.js”).Include(“~/js/JavaScript1.js”));
//another way
//var bootstrapCss = new Bundle(“~/bootstrap/css”, new CssMinify());
//bootstrapCss.Include(“~/css/StyleSheet1.css”);
//bootstrapCss.Include(“~/css/StyleSheet2.css”);
//bundles.Add(bootstrapCss);
//var bootstrapJs = new Bundle(“~/bootstrap/js”, new JsMinify());
//bootstrapJs.Include(“~/js/jquery-2.1.1.js”);
//bootstrapJs.Include(“~/js/JavaScript1.js”);
//bundles.Add(bootstrapJs);
}
}
4. Now go to global.asax.cs file and add
BundleConfig.RegisterBundles(BundleTable.Bundles);
BundleTable.EnableOptimizations = true;
44

5. a) make sure debug is set to false in the web.config file of the application
b) and under <system.web> <pages><namespaces> tag add
  <add namespace=”System.Web.Optimization”/>
6. now we will go to view page(.cshtml) and add the js and css bundle references
66
@using System.Web.Optimization;
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
@Styles.Render(“~/bundles/mycss”)
@Scripts.Render(“~/bundles/jsbundle”)
<title>Samplepage</title>
</head>
<body>
<div>
<h1>Hi welcome to my site</h1>
<p>Enter your Name:</p>
<input id=”txtName” type=”text”/>
<button onclick=”message();”>Enter</button>
</div>
</body>
</html>

now lets run the application to check
output:
1. Before Bundling
22
2. After Bundling ( Check the time )
77

asp.net mvc validations using dataannotations

hi lets see how to do validation in asp.net mvc using dataannotations
so lets start implementing this.

1. first create a model :
public class DataForm
{
[Key]
public int EMPID { get; set; }
[StringLength(60, MinimumLength = 3,ErrorMessage=”Min String length is 3″)]
public string EMPNAME { get; set; }
[Required(ErrorMessage=”Field should not be empty”)]
public string EMPADD { get; set; }
[RegularExpression(@”^[0-9]{0,8}$”, ErrorMessage = “Salary should be Numeric”)]
public string EMPSAL { get; set; }
}
here in the above model we will define the form fields and the validation messages. we also need to add below namespace
using System.ComponentModel.DataAnnotations;
_1


2. after this go to controller and add two action methods.
httppost action method will only accept the postback requests like the submit, create.
public ActionResult data() // will be called intially
{
return View();
}
[HttpPost]
public ActionResult data(DataForm d1) // will handle postback requests
{
if (ModelState.IsValid)
{
return RedirectToAction(“saveData”);
}
return View(d1);
}

_2
3. now add a strongly typed view using model DataForm and using scaffold template as create.

1
@model mvcFilters.DataForm
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>data</title>
</head>
<body>
<script src=”~/Scripts/jquery-1.8.2.min.js”></script>
<script src=”~/Scripts/jquery.validate.min.js”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js”></script>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>DataForm</legend>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPNAME)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPNAME)
@Html.ValidationMessageFor(model => model.EMPNAME)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPADD)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPADD)
@Html.ValidationMessageFor(model => model.EMPADD)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPSAL)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPSAL)
@Html.ValidationMessageFor(model => model.EMPSAL)
</div>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}
<div>
@Html.ActionLink(“Back to List”, “Index”)
</div>
</body>
</html>
now run the project to check if the validations are working properly.
output:
2

Exception handling in asp.net mvc using HandleError Attribute

hi in this post i will show how to use handleError attribute for exception handling in asp.net mvc.

we can add handleError attribute around the whole controller class or just around the individual action methods.
1
next we need to add
<customErrors mode=”On”></customErrors> 
in the webconfig file.
10-25-2014 8-51-02 PM

Now in the view folder we will create a shared folder and in that we will add a view page called error.cshtml
so whenever there is any exception it will get redirected to this page.
we will create a strongly typed view which will have model HandleErrorInfo
error.cshtml code:
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>error</title>
</head>
<body>
<div>
Error Occured !!!
<table border=”1″>
<tr>
<td>
Controller Name: @Model.ControllerName
</td>
<td>
Action Name: @Model.ActionName
</td>
<td>
Exception Details: @Model.Exception
</td>
</tr>
</table>
</div>
</body>
</html>
model HandleErrorInfo code :
public class HandleErrorInfo
{
public string ActionName { get; set; }
public string ControllerName { get; set; }
public Exception Exception { get; set; }
}

Output:
Now run the application
error

Implementing Asp.net Custom MVC filters [Part 2]

hi in this post i will show an another way implementing custom asp.net mvc filters.
Now i will create separate class for every filter types which will inherit attributes according to type and then we will implement that inherited methods.
here we will use the name of filter class and add it on the top of action method or we can also add it to the whole controller.
Code :
1
Controller :
[CustomAuthorization]
public class MainController : Controller
{
//
// GET: /Main/
[CustomAction]
[CustomExceptionFilter]
public ActionResult Index()
{
int i = Convert.ToInt32(“1″) / Convert.ToInt32(“0″);
ViewBag.message = “hello world”;
return View();
}
}
class CustomAuthorization : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.Controller.ViewBag.AuthorizationMsg = “From OnAuthorization method”;
}
}
class CustomAction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ActionExecutingMsg = “From OnActionExecuting method”;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.ActionExecutedMsg = “From OnActionExecuted method”;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ResultExecutingMsg = “From OnResultExecuting method”;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.Controller.ViewBag.ResultExecutedMsg = “From OnResultExecuted method”;
}
}
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult
{
ViewName = “error”,
};
}
}
View:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.message
<br />
@ViewBag.AuthorizationMsg
<br />
@ViewBag.ActionExecutingMsg
<br />
@ViewBag.ActionExecutedMsg
<br />
@ViewBag.ResultExecutingMsg
<br />
@ViewBag.ResultExecutedMsg
<br />
@ViewBag.ExceptionMsg
</div>
</body>
</html>

I’m adding one more view named error.cshtml , to which we will redirect when any exception occurs.
2



Output:
1. Without Exception
1
2. With Exception
2