Change Response From Xml to Json in ASP.NET MVC WepApi

By default in ASP.NET MVC WepApi  the response format of Restful methods is XML. You can change this to JSON by simply removing the current response format like below in WepApiConfig

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

//Code for removing the current response format
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}

Enjoy coding..

IValidatableObject interface in .Net Framework4 (System.ComponentModel.DataAnnotations)

Along with DataAnnotations validations .NET framework brought us the IValidatableObject interfaces which let us built the type level validations rules. Beginning with MVC3 IValidatableObject is honored by MVC3 validation API and EntityFramework validation API will also check any IValidatableObject.
Here it is bits of code showing the Person class implements the interface along with validate method. One simple rule checking here is the Name matches with Email address if they do the validation fail and method returns the validation result.
IValidate

Let see how this works with the automatic save changes validation before we really dig in to see what’s going on.

valExee

Above is a bit of codes for inserting Person in to the db using Enityframework which results a two validation errors .The first one is Name cannot match Email associated with the property Name and the second is same error Name cannot match Email ,this time with property name Email. Why that is?
When we look in to validate method in the domain class I built this validation result I gave it not only the error message that I want to be displayed list of the property is associated with it, this is literally the property names. The reason those property names are there is because If I am going to be take the advantage of one of the framework that is client side validation in MVC. MVC is going to read this validation result and to apply error message next to where the Name property is to be displayed and where the Email property is to be displayed.

Introduction to ASP.NET MVC

Introduction to ASP.NET MVC

ASP.NET MVC is a UI technology  based on Model,View,Controller design pattern. In the MVC pattern use separate UI code in to distinct components.You have model,view and controller

 MVC

 

                Model contain data to be displayed and some associated logic. The Controllers are responsible for recieving a request and figuring  out what to do, they often build the model and they select a view to build the model. The view is only responsible for taking the model from the controller and producing the html that you see in the browser. Each component has distinct responsibilities

 How ASP.NET MVC works?

 page

                When i make a request to the browser for example localhost:49169 the runtime will looking for a controller to process this request. MVC is working on the basis of routing logic. Routing is something configured on the start of the application that is inside Global.asax.

Route specify a pattern that the runtime match against the incoming URL.

route

The method RegisterRoutes() configured in the Application_Start method of a Global.asax file which is responsible for handling the incoming URL.We can specify the default Controller and action inside the register routes method.

Whenever i making a request for example localhost:49169 without specifying the controller and action in the url the routing mechanism of ASP.NET MVC takes the default controller and action such as Home and index. That means i can make request to localhost:49169/home that arrives the homepage and i can make request to localhost:49169/home/index  that arrives the same page. If i am try to specify that doesn’t exist  for example localhost:49169/hello and there is no hello controller and i get back an Http 404 error like below.

error

Enjoy reading….

Sending Ajax Request when Dropdown change in ASP.NET MVC

Introduction

This is a simple example which send an ajax request to the ActionResult and return a JsonResult.

jQuery script for sending the request

jQuery(document).ready(function(){
$("#YourDropDownId").change(function() {
var ServiceUrl ="/YourController/Action?id=" + 1;
var content = '';
$.support.cors = true;
$.ajax({
type: 'GET',
url: ServiceUrl,
async: true,
cache: false,
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: 'json',
error: function (xhr, err) {
},
success: function (result, status) {
$('#yourTextId').val(result.Value);
}
});
});
});

ActionResult

[HttpGet]
public ActionResult Action(int id)
{
var result = new { Value = "my Json result" };
return Json(result, JsonRequestBehavior.AllowGet);
}

Enjoy Coding…

Html.Partial,Html.RenderPartial,Html.Action and Html.RenderAction in ASP.NET MVC

Html.Partial and Html.RenderPartial     

  The Html.Partial helpers renders a partial view in to string.You can reuse this Partial Views in Multiple Views. Partial has four overloads
public void Partial(string partialViewName);

public void Partial(string partialViewName, object model);

public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,ViewDataDictionary viewData);
 Example : 
 @Html.Partial("MyPartial")
 
Difference Between Render Partial and Partial

RenderPartial writes directly to the response output stream instead of returning a string. So, you should place RenderPartial inside a code block instead of a code expression

Example :
 @{Html.RenderPartial("MyRenderPartial");}

 So, which should you use, Partial or RenderPartial?

In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream.

Html.Action and Html.RenderAction

         Html.Action and Html.RenderAction are similar to Partial and RenderPartial.Action  executes a separate controller action and display the results.the only difference between Action and RenderAction is that RenderAction writes directly to the response.

 Example :
Imagine you are using the following controller
public class ActionDemoController : Controller {
public ActionResult Index() {
return View();
}

[ChildActionOnly]
public ActionResult DisplayMenu() {
var menu = GetMenuFromSomewhere();
return PartialView(menu);
}
}

The Menu action builds a menu model and returns a partial view with just the menu:
@model Menu
<ul>
@foreach (var item in Model.MenuItem) {
<li>@item.Text</li>
}
</ul>
In your Index.cshtml view, you can now call into the Menu action to display the menu:
<html>
<head><title>Index with Menu</title></head>
<body>
@Html.Action("DisplayMenu")
<h1>Welcome to the Index View</h1>
</body>
</html>

Notice that the Menu action is marked with a ChildActionOnlyAttribute. The attribute prevents the runtime from invoking the action directly via a URL. Instead, only a call to Action or RenderAction can invoke a child action. The ChildActionOnlyAttribute isn’t required, but is generally recommended for child actions.
Passing values to Action
       Sometimes you want to pass parameters in to the action.
Example:
[ChildActionOnly]
public ActionResult Menu(MenuParameters param) {
return PartialView(
param);

}

@Html.Action(“Menu”, new {options = new MenuParameters { Width=400, Height=500 } })

Enjoy Coding…

Load Partial View as Html By using jQuery – Ajax in ASP.NET MVC

Introduction

In ASP.NET MVC we can return a Partial View in the form of PartialViewResult using the PartialView method.
The following example shows Partial update scenarios using Ajax.Using jQuery to load the contents of a PartailView in to the current view using an Ajax call. In this example i have load a simple grid using Ajax.
Controller and Action Result

public class PartialController : Controller
{
public ActionResult GetPartialResult()
{
var list = new List<Album>
{
new Album {Title = "Album1"},
new Album {Title = "Album2"},
new Album {Title = "Album3"},
new Album {Title = "Album4"}
};
return PartialView(list);
}

}

public class Album
{
public string Title { get; set; }
}

Right click the ActionResult and Create a PartialView like below
@model IEnumerable<Mvc4Demos.Controllers.Album>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
</tr>
}
</table>

Here when a button click load the PartialViewResult by using Ajax and Append in to a Result div
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#result').load('/Partial/GetPartialResult');
});
});

</script>
<input type="button" id="btn" value="PartialExample"/>
<div id="result"></div>

Enjoy Reading…