Tuesday, 15 January 2013

Basic Links for MVC Developers


jQuery
==================
Async Call
-----------

http://forums.asp.net/t/1741929.aspx/1
http://api.jquery.com/jQuery.getJSON/


Entity Framework
==================
EF 4 Tutorial
---------------

http://www.entityframeworktutorial.net/entityframework4.aspx


DB First
-----------
http://programmaticponderings.wordpress.com/2012/11/22/first-impressions-of-database-first-development-with-entity-framework-5-in-visual-studio-2012/

http://msdn.microsoft.com/en-us/data/jj206878.aspx

Calling Stored Procedures
----------------------------

http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values


Simple Unit Of Work
--------------------

http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

Generic Unit Of Work
---------------------

http://blog.damianbrady.com.au/2012/07/24/a-generic-repository-and-unit-of-work-implementation-for-entity-framework/

Multiple Submit Button on MVC page



Thanks to
http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx


public class HttpParamActionAttribute : ActionNameSelectorAttribute {
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
            return false;
        
        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}
How to use it? Just have a form similar to this:
<% using (Html.BeginForm("Action", "Post")) { %>
  <!— …form fields… -->
  <input type="submit" name="saveDraft" value="Save Draft" />
  <input type="submit" name="publish" value="Publish" />
<% } %>
and controller with two methods
public class PostController : Controller {
    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SaveDraft() {
        //…
    }

    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Publish() {
        //…
    }
}
As you see, the attribute does not require you to specify anything at all. Also, name of the buttons are translated directly to the method names. Additionally (I haven’t tried that) these should work as normal actions as well, so you can post to any of them directly.

Monday, 14 January 2013

Async Call using Ajax


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PCO.Web3.Models;

namespace PCO.Web3.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }


        [HttpGet]
        public ActionResult Employees()
        {
            return View();
        }

        [HttpGet]
        public ActionResult ListEmployee(string id, Int64 age=0)
        {
            EmployeeViewModel model = new EmployeeViewModel();
            model.Name=id ;
            model.Age= age ;

            return PartialView(model);
        }

        public JsonResult GetEmployeeList(string id, Int64 age = 0)
        {
            List<EmployeeViewModel> model = new List<EmployeeViewModel>();
            model.Add(new EmployeeViewModel() { Name = "Puru", Age=36, Salary=5000});
            model.Add(new EmployeeViewModel() { Name = "Puru1", Age = 36, Salary = 5000 });
            model.Add(new EmployeeViewModel() { Name = "Puru2", Age = 39, Salary = 8000 });
            model.Add(new EmployeeViewModel() { Name = "Puru3", Age = 34, Salary = 6000 });

            return  Json(model, JsonRequestBehavior.AllowGet);
        }
    }
}



HTML


@model  PCO.Web3.Models.EmployeeViewModel

@{
    ViewBag.Title = "Employees";
}

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#btnSearch").click(function () {
            //GetList();
            //GetListUsingAjax();
            GetJsonListUsingAjax();
        });
    });


    function GetListUsingAjax() {
        var strName = $("#Name").val();

        var targetUrl = "/home/ListEmployee/" + strName;

        $.ajax({
            url: targetUrl,
            dataType: 'text',
            data: { id: strName, age: $("#Age").val() },
            success: function (bsHTML) {
                alert(123456);
                $("#listContainer").html(bsHTML);
            },
            error: function (req, status, ex) {
                alert(2);
            }
        });
    }

    function GetJsonListUsingAjax() {
        var strName = $("#Name").val();

        var targetUrl = "/home/GetEmployeeList/" + strName;

        $.ajax({
            url: targetUrl,
            dataType: 'json',
            data: { id: strName, age: $("#Age").val() },
            success: function (bsHTML) {
                alert(bsHTML[1].Name);
                $("#listContainer").html(bsHTML.name[1]);
                
            },
            error: function (req, status, ex) {
                alert(ex);
            }
        });
    }


    function GetList() {
        var strName = $("#Name").val();

        var url = "/home/ListEmployee/" + strName;
        $("#listContainer").load(url);
        $("#partialHeader").load(url);

        return false;
    }
</script>

<h2>Employees</h2>

@using (Html.BeginForm())
    @Html.LabelFor(x => x.Name)
    @Html.TextBoxFor(x => x.Name)

    @Html.LabelFor(x => x.Age)
    @Html.TextBoxFor(x => x.Age)

    //@Html.ActionLink("Search", "ListEmployee", new { id = 1})
    <input id="btnSearch" type="button" value="Search"/>
    
    <div id="listContainer">
    
    </div>
    
}


Dpendency Resolver Using Ninject


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ninject;
using Ninject.Syntax;

namespace BasicMVCDemo.Infrastructure
{
    public class NinjactDependencyResolver: IDependencyResolver
    {

        private readonly IResolutionRoot _resolutionRoot;

        public NinjactDependencyResolver(IResolutionRoot kernel)
        {
            _resolutionRoot = kernel;
        }

        public object GetService(Type serviceType)
        {
            return _resolutionRoot.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _resolutionRoot.GetAll(serviceType);
        }
    }
}

Setting in Global.asax


public void SetupDependencyInjection()
        {
            // Create Ninject DI kernel
            IKernel kernel = new StandardKernel();

            // Register services with Ninject DI Container
            kernel.Bind<DbContext>().To<DBFirstDemoEntities>();
            kernel.Bind<ICustomerRepository>().To<CustomerRepository>();

            // Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjactDependencyResolver(kernel));
        }

DB Connection

<add name="DBFirstDemoEntities" connectionString="Server=(local);Database=DBFirstDemo;Trusted_Connection=True;" providerName="System.Data.SqlClient" />

OnModelCreating


protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //throw new UnintentionalCodeFirstException();
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new ArticleConfiguration());

        }

DbConfiguration


public class ArticleConfiguration : EntityTypeConfiguration<Article>
{
   public ArticleConfiguration()
   {
      this.HasMany(x=>x.RelatedArticles)
         .WithMany(x=>x.OtherRelatedArticles)
         .Map(x=>x.ToTable("RelatedArticles"));
   }
}