Binding and Posting a Collection of Custom types in ASP.NET MVC.

In ASP.NET MVC we can simply bind and post a custom type of collection. Here I am demonstrating a sample application for implementing this.
Create a sample class of type Person
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Create a controller with two action such as Index for loading a List and Register for posting List
public class PersonController : Controller
{
public ActionResult Index()
{
var persons = new List()
{
new Person {FirstName = "Jameel", LastName = "VM"},
new Person {FirstName = "Jasin", LastName = "VM"}
};
return View(persons);
}
[HttpPost]
public ViewResult Register(List persons )
{
return View();
}
}
}

Index view code for looping the person collection and also I had put a form tag which map to Register action for posting the edited collection

code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

When we click the register button the form will post the collection of values to Register action like below

1

2

Loading DropdownList in ASP.NET MVC

In ASP.NET MVC you can load DropDownList easily. There are different ways for loading this. Here I am demonstrating a simple example for loading some countries.
Create a Generic class DropDownList<T> which contain a method LoadItems which return Sytem.Web.Mvc.SelectList
public static class DropDownList<T>
{
public static SelectList LoadItems(IList<T> collection, string value, string text)
{
return new SelectList(collection, value, text);
}
}

Create two class such as Country and a CountryViewModel which contain  a property for getting PostedCountryId
public class CountryViewModel
{
public int PostedCountryId { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}

Then I am going to fill the countries list in to a ViewData. You can also use ViewBag instead
public class DropDownController : Controller
{
public ActionResult Index()
{
ViewData["LoadCountries"] = DropDownList<Country>.LoadItems(CountriesCollection(), "Id", "Name");
return View();
}
public List<Country> CountriesCollection()
{
var list = new List<Country>
{
new Country{Id = 1,Name = "India"},
new Country{Id = 2,Name = "Brazil"},
new Country{Id = 1,Name = "Gautemala"},
new Country { Id = 1,Name = "Spain"}
};
return list;
}
}

From the view you can retrieve the ViewData value to DropDownListFor helper
@model MVCCollection.Controllers.CountryViewModel
@using (Html.BeginForm("Create", "DropDown", FormMethod.Post))
{
@Html.DropDownListFor(model => model.PostedCountryId, (IEnumerable<SelectListItem>) ViewData["LoadCountries"], "--Select--", new {@class = "select"})
<input type="submit" value="PostSelectedCountryId"/>
}

When you call the submit button you will get selected country id to CountryViewModel class like below
1

Enjoy coding…

Post data to the action result in jqGrid and ASP.NET MVC

Below example shows how to postdata from the jQGrid to ASP.NET MVC ActionResut when dropdown change

Script


$(".selectRequestType").change(function () {
$('#jqgRequests').setGridParam({ postData: { FilterValue: $(this).val() } }).trigger('reloadGrid', [{ page: 1 }]);
});

Action Result


[AcceptVerbs(HttpVerbs.Post)]
public JsonResult LoadRequest(JqGridRequest request, PostDataViewModel postData)
{
}

public class PostDataViewModel
{
public string FilterValue { get; set; }
}

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…