Monday 28 October 2013

MVC Tips : Set Default Route Value in ASP.Net MVC 4

Click Here to Download SetDefaultRouteInMVC.zip Example.

You can set Default route value for URL in MVC. Traditional our route pattern is like '{controller}/{action}/{id}'. This is going to fail if we pass URL like '{controller}/{action}'.

There are many scenarios in our day to day software application we require both pattern. For that you can set 'Id' as default parameter so that if we did not pass 'id' in query string it will not raise errors and execute our desired 'action'.

We can configure Route in 'App_Start/RouteConfig.cs' file using this 'routes.MapRoute' method, where 'routes' is the object of 'RouteCollection' class. In 'MapRoute' method we can set Default values. Code is something like below :
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { id = UrlParameter.Optional }
    );

Here is example for this. 

In this example we are listing all customer using 'list' action. For this, URL looks like this 'Customer/List'. If we did not set optional for 'id' parameter it will raise error or else we need to configure other MapRoute for '{controller}/{action}' pattern.

Now for editing of customer we use this type of URL 'Customer/Edit/1'. So setting optional 'id' parameter, our both URLs are working fine with single MapRoute registration. Here is code for this.

Route Config (RouteConfig.cs) : 
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { id = UrlParameter.Optional }
            );
        }
    }

Model (Customer.cs): 
    public class Customers
    {
        public int CustomerId;
        public string FirstName;
        public string LastName;
        public int Rank;

        public static List<Customers> GetCustomersList()
        {
            List<Customers> lstCustomers= new List<Customers>();
            Customers objCustomers;

            objCustomers = new Customers();
            objCustomers.CustomerId=1;
            objCustomers.FirstName="Sachin";
            objCustomers.LastName="Tendulkar";
            objCustomers.Rank=1;
            lstCustomers.Add(objCustomers);

            objCustomers = new Customers();
            objCustomers.CustomerId = 2;
            objCustomers.FirstName = "Lionel";
            objCustomers.LastName = "Messi";
            objCustomers.Rank = 5;
            lstCustomers.Add(objCustomers);


            objCustomers = new Customers();
            objCustomers.CustomerId = 3;
            objCustomers.FirstName = "Cristiano ";
            objCustomers.LastName = "Ronaldo";
            objCustomers.Rank = 6;
            lstCustomers.Add(objCustomers);


            objCustomers = new Customers();
            objCustomers.CustomerId = 4;
            objCustomers.FirstName = "Rahul";
            objCustomers.LastName = "Dravid";
            objCustomers.Rank = 2;
            lstCustomers.Add(objCustomers);


            objCustomers = new Customers();
            objCustomers.CustomerId = 5;
            objCustomers.FirstName = "Brad";
            objCustomers.LastName = "Pitt";
            objCustomers.Rank = 3;
            lstCustomers.Add(objCustomers);
            
            return lstCustomers;
        }
    }

Customer Controller (CustomerController.cs) :
    public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult List()
        {
            List<Customers> lstCustomers = Customers.GetCustomersList();
            return View(lstCustomers);
        }

        public ActionResult Edit(int id)
        {
            List<Customers> lstCustomers = Customers.GetCustomersList();
            Customers objCustomer=(from m in lstCustomers where m.CustomerId==id select m).SingleOrDefault();

            return View(objCustomer);
        }


    }

List View(List.chtml) :
@model IEnumerable<SetDefaultRoute.Models.Customers>

@{
    ViewBag.Title = "List";
}

<h2>List</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>Customer Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Rank</th>
    </tr>

    @foreach (var item in Model)
 {
        <tr>
            <td>@Html.DisplayFor(model => item.CustomerId)            </td>
            <td>@Html.DisplayFor(model => item.FirstName)</td>
            <td>@Html.DisplayFor(model => item.LastName)</td>
            <td>@Html.DisplayFor(model => item.Rank)</td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.CustomerId }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
 }

</table>

Edit View (Edit.chtml) :
@model SetDefaultRoute.Models.Customers

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Customers</legend>
        <table>
            <tr>
                <td>
                    @Html.LabelFor(model => model.FirstName)
                </td>
                <td>
                    @Html.EditorFor(model => model.FirstName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.LastName)
                </td>
                <td>
                    @Html.EditorFor(model => model.LastName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.Rank)
                </td>
                <td>
                    @Html.EditorFor(model => model.Rank)
                </td>
            </tr>
            
        </table>
        
        
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Output : 

      Listing URL :


       Edit URL :


Below are the books that you would like :

No comments:

Post a Comment