Thursday, 15 March 2012

How to use MVC3 with AJAX

To enable AJAX calls add this line to Views/Shared/_Layout.cshtml

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

Add new Products tab to menu in Views/Shared/_Layout.cshtml

<li>@Html.ActionLink("Product", "Index", "Product")</li>

Create new controller Controllers/ProductController.cs

DatabaseEntities is the Entity Framework 4 model with single table Product with 2 columns (Id uniqueidentity, Name nvarchar(100))

public class ProductController : Controller
{
    DatabaseEntities entities = new DatabaseEntities();
    public ActionResult Index()
    {
        return View(entities.Products);
    }
    [HttpPost]
    public ActionResult AddProduct(string name)
    {
        var product = new Product();
        product.Id = Guid.NewGuid();
        product.Name = name;
        entities.Products.AddObject(product);
        entities.SaveChanges();
        return PartialView("ProductList", entities.Products);
    }
    public ActionResult DeleteProduct(Guid id)
    {
        entities.Products.DeleteObject(entities.Products.FirstOrDefault(x=>x.Id==id));
        entities.SaveChanges();
        return PartialView("ProductList", entities.Products);
    }
}

Create 2 views /Views/Product/Index.cshtml

@using System.Data.Objects
@using MyProject.Data
@{
    ViewBag.Title = "Products";
}
@using (Ajax.BeginForm("AddProduct", "Product",new AjaxOptions()
    {
        UpdateTargetId = "ProductListDiv",
        HttpMethod = "POST"                                                                                  
    }))
{
    @Html.Label("Name: ") @Html.TextBox("name")
    <input type="submit" value="+" />     
}
<div id="ProductListDiv">
@Html.Partial("ProductList", (ObjectSet<Product>)Model)  
</div>

And /Views/Product/ProductList.cshtml

@using MyProject.Data
<table>
@{
    if (Model != null)
    {
        foreach (var m in Model)
        {
          <tr>
            <td>
                @Ajax.ActionLink("Delete", "DeleteProduct", "Product", new { Id = m.Id }, new AjaxOptions()
           {
               UpdateTargetId = "ProductListDiv",
               HttpMethod = "POST"
           })
           </td>
           <td>
                @m.Name
            </td>
        </tr>             
        }
    }
}
</table>

it should look more less like this

Mvc3Ajax

No comments:

Post a Comment