:::: MENU ::::

Monday, February 13, 2012

 
url: "Customers/{id}",
        defaults: new { controller = "Customer", action = "Get" },
        constraints: new { httpMethod = new HttpMethodConstraint("GET") }
        );
  
     routes.MapRoute(
         name: "CustomerUpdate",
         url: "Customers/{id}",
         defaults: new { controller = "Customer", action = "Update" },
         constraints: new { httpMethod = new HttpMethodConstraint("POST") }
         );
  
     routes.MapRoute(
         name: "MVC Default",
         url: "{controller}/{action}/{id}",
         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
     );
  
    
 }

You can override the default route for "Customers/{id}" for getting or updating an specific customer by using an http method constraint. I also added the first  route for adding a new customer so the "Add" segment is not used as the "{id}" wildcard.

As you could see, we could split all the responsibilities in two controllers, which look simpler at first glance. In conclusion, you don't need to assume the same URL means the same controller.

The "delete" action is implemented as an http post. This can be sent from the browser by using an Ajax call or a Http form. For example, the following code shows how to do that using a JQuery Ajax call.

 @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "delete" })
 <script type="text/javascript" language="javascript">
    1:  
    2:     $(function () {
    3:         $('.delete').click(function () {
    4:             var that = $(this);
    5:             var url = that.attr('href');
    6:  
    7:             $.post(url, function () {
    8:                 alert('delete called');
    9:             });
   10:  
   11:             return false;
   12:         });
   13:     });
</script>
The code is available for download from here

More