Wednesday, January 2, 2013

asp.net mvc check box list helper

Following is a simple asp.net mvc Extension/Helper method to create a checkbox list.

This method takes IEnumerable list, name for the list, number of columns per row, html attributes(if any) as parameters.


public static class CheckBoxExtension
{

public static MvcHtmlString CheckBoxList(this HtmlHelper helper, IEnumerable<SelectListItem> items,
                                    string name, int columns, object htmlAttributes)
        {
           //Build a string builder
            var output = new StringBuilder();
            output.Append("<div>");
            output.Append("<table><tr>");
            int itemCount = 0;
         
            //Loop through items and generate checkbox list.
            foreach (var item in items)
            {
                itemCount++;
                output.Append("<td style='white-space:normal;'>");
                var checkboxList = new TagBuilder("input");
                checkboxList.MergeAttribute("type", "checkbox");
                checkboxList.MergeAttribute("name", name, true);
                checkboxList.MergeAttribute("ID", name + "-" + item.Value, true);
                checkboxList.MergeAttribute("value", item.Value);

                if (!ReferenceEquals(htmlAttributes, null))
                    checkboxList.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));

                // Check to see if it's checked                  
                if (item.Selected)
                    checkboxList.MergeAttribute("checked", "checked");
             
                checkboxList.SetInnerText(item.Text);
                output.Append(checkboxList.ToString(TagRenderMode.SelfClosing));
                output.Append("&nbsp;");
                output.Append(item.Text);

                //List alignment as per number of columns specified
                if ((itemCount % columns) == 0)
                {
                    output.Append("</td>");
                    output.Append("</tr>");
                    output.Append("<tr>");
                }
                else
                {
                    output.Append("</td>");
                }
            }
            output.Append("</tr></table>");
            output.Append("</div>");

            return MvcHtmlString.Create(output.ToString());
        }


}

add above class to your project.

You can call the above helper in the View as follows

@using "namespace where extesion method is defined"


@{
    var dayList = new List<SelectListItem>
                        {
                            new SelectListItem
                            {
                                Text = "Sunday",
                                Value = "1",
                                Selected = true
                            },
                         
                            new SelectListItem
                            {
                                Text = "Monday",
                                Value = "2",
                                Selected = false
                            },
                         
                            new SelectListItem
                            {
                                Text = "Tuesday",
                                Value = "3",
                                Selected = true
                            },
                        };
    }

//call to the helper

@Html.CheckBoxList(dayList, "Days", 3, null)

Output will be as follows :



That's it your extension mehod is ready.

Feel free to comment..

Thursday, April 19, 2012

Teleik MVC Grid Ajax edit and drop down binding

Are you using telerik grid control in your MVC3 application and you need to bind dropdown on edit dynamically based on the row selection, here is the example for you which displays a grid with customers and their states and on editing a customer we bring data of states based on customer id and show them in a drop down in the grid.

Controller: ~/Controller/HomeController.cs

public class HomeController
{

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

     [GridAction]
     public ActionResult _GetCustomers()
        {
            // do your stuff here to get customer's data
            return View(
                new GridModel<testModel1>{
                    Data = db.GetCustomers()
                }
                );
        }


[GridAction]
        [HttpPost]
        public ActionResult _UpdateCustomer(testModel1 objTest)
        {
            // update the customer
            return View(
                new GridModel<testModel1>
                {
                    Data = db.GetCustomers()
                }
                );
        }

       public JsonResult GetStatesOnCustomer(int CustId)
        {
            var states = new SelectList(GetStates(CustId), "St_Id", "St_name");
            return Json( states , JsonRequestBehavior.AllowGet);
        }

}


Model class:

public class testModel1
    {
        public int CustId { get; set; }
        public int StateId { get; set; }
       // This is the key for grid to find out the name of display and editor templates
        [UIHint("State"), Required]
        public string State { get; set; }
    }

public class States
{
       public int St_Id { get; set; }
       public string St_name { get; set; }
}


Telerik grid  ~/Views/Customers.cshtml



function onSave(e) {
        var selected = $(e.form).find('# ddState ').val();
        if (selected == 0) {
            alert("Please select a state");
            return false;
        }
    }

    function onEdit(e) {
       //Get the customer id from the row selected
        var custId = parseInt(e.dataItem['CustId']);
       //get the dom instance of state drop down
        statedd = $(e.form).find('#ddState').data('tDropDownList');
       // make a ajax call to the controller with customer id as parameter to fetch states dynamically based on   customer id
        $.ajax({
            type: "GET",
            async: false,
            cache: false,
            url: '@Url.Action(" GetStatesOnCustomer ", "Home")',
            dataType: 'json',
            data: { CustId:  custId  },
            success: function (states) {
                var prop;
                var propCount = 0;
                for (prop in  states )
                    propCount++;

                if (propCount > 0) {
                    //bind the returned value to the state drop down
                     states .splice(0, 0, { Selected: false, Text: '--Select--', Value: 0 });
                     statedd  .dataBind(suppliers);
                     statedd  .reload();
                     statedd  .select(function (dataItem) {
                        return dataItem.Value == e.dataItem['StateId'];
                    });
                }
                else {
                    $('a[class="t-button t-grid-cancel"]').click();
                    alert("States not found");
                }
            },
            error: function () {
                alert('Failed to retrieve states.');
            }
        });
    }



@(Html.Telerik().Grid<testModel1>()
.Name("testGrid")
.DataKeys(keys =>
{
keys.Add(o => o.CustId);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_GetCustomers", "Home")
.Update("_UpdateCustomer", "Home");
})
.Columns(columns =>
{
columns.Bound(o => o.CustId).Width(100);
columns.Bound(o => o.State).Width(230);
columns.Command(commands => commands.Edit()).Title("Edit").Width(200);
})
.ClientEvents(events=>events.OnSave("onSave").OnEdit("onEdit"))
.Pageable()
)

Display Template: ~/Views/DisplayTemplates/State.cshtml

@model testModel1
@Model.State

Editor Template:  ~/Views/EditorTemplates/ State.cshtml

@using Telerik.Web.Mvc.UI
@(Html.Telerik().DropDownList() .Name("ddState").HtmlAttributes(new { width="100"}) )


Things to remember:
1)Create display and editor templates in the folder structure as specified in bold
2)UIHint must be defined in the Model(as we did for State in testModel1.cs)
3)Finally specify all the telerik references that are required for the Grid(You can find it here)

Feel free to comment..

Tuesday, April 17, 2012

ASP.Net MVC3 Ajax form submission using JQuery Ajax

This is a continuation for my previous article
http://mvc3only.blogspot.in/2012/04/aspnet-mvc3-ajax-form-submission-simple.html

where we learnt how to submit form using Asp.net mvc Ajax Beginform.

This post is for people who want to submit their form using JQuery Ajax options
Now using the same code as mentioned in ASP.Net MVC3 Ajax form submission simple example article with some modifications in the "testCreate.cshmtl" view we can submit the form using JQuery Ajax as follows.

Use the same code mentioned in the above and make some modification's in testCreate.cshmtl as follows
Views: 
~/Home/testCreate.cshtml



@model MvcApplication1.Models.testModel1
@{
    ViewBag.Title = "testCreate";
}


<script type="text/javascript">


    $(document).ready(
    function () {


        $('#frmTestCreate').live('submit', function (e) {
            e.preventDefault();
            $('#btnSubmit').attr('disabled', 'disabled');
            $('#loading').show();
            $.ajax(
            {
                cache: false,
                async: true,
                type: "POST",
                url: $(this).attr('action'),
                data: $(this).serialize(),
                success: function (data) {
                    $('#result').empty();
                    $('#result').html(data);
                },
                complete: function () {
                    $('#loading').hide();
                    $('#btnSubmit').removeAttr('disabled');
                }
            }
            );
        }
        );
    }
    );


</script>


<h2>testCreate</h2>
<div id="loading" style="display:none; font-size:large; font-weight:bold">....Updating....</div>


@using (Html.BeginForm("testCreate", "Home", FormMethod.Post, new { id = "frmTestCreate" }))
{
    <table>
        <tr>
            <td>
                First Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                Last Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.LastName)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="btnSubmit" type="submit" value="Submit" />
            </td>
        </tr>
    </table>
}


<div id="result" style="color: Green;"></div>


This modification will make form submitted via JQuery Ajax. That's it we are done.


Feel free to comment..

ASP.Net MVC3 Ajax form submission using Ajax.BeginForm simple example

Hey MVC3 begginer's


Here is a simple example of using asp.net mvc3 Ajax.BeginForm to submit forms with out regular post backs. In order to understand the following stuff you need to have basic knowledge of creating basic MVC3 application.


Controller: HomeController.cs

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

namespace MvcApplication1.Controllers// change name spaces as required
{
    public class HomeController : Controller
    {
        //Action Method to display testCreate view
        public ActionResult testCreate()
        {
            var model = new MvcApplication1.Models.testModel1();
            return View(model);
        }

        //Action method that handles the testCreate form submission
        [HttpPost]
        public PartialViewResult testCreate(MvcApplication1.Models.testModel1 testModel)
        {
            System.Threading.Thread.Sleep(5000);// you can do your updating stuff here
            if (ReferenceEquals(testModel.FirstName, null))
                testModel.FirstName = string.Empty;
            if (ReferenceEquals(testModel.LastName, null))
                testModel.LastName = string.Empty;
            return PartialView("testPartial", testModel);
        }
    }
}

Model: testModel1.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    //Model created to bind data to testCreate view
    public class testModel1
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Views: 
~/Home/testCreate.cshtml



@model MvcApplication1.Models.testModel1
@{
    ViewBag.Title = "testCreate";
}

<script type="text/javascript">
    //Method that will be on begin of Ajax request, here we are displaying some text to user while update is    //going on
    function onBegin() {
        $('#loading').show();
    }

    //Method that will be called once ajax request was done and we will hide the loading text
    function onComplate() {
        $('#loading').hide();
    }

</script>

<h2>testCreate</h2>
<div id="loading" style="display:none; font-size:large; font-weight:bold">....Updating....</div>

@using(Ajax.BeginForm("testCreate","Home",new AjaxOptions{ HttpMethod="POST", UpdateTargetId = "result", OnBegin = "onBegin()", OnComplete = "onComplate()" }))
{
    <table>
        <tr>
            <td>
                First Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                Last Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.LastName)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Submit" />
            </td>
        </tr>
    </table>
}

<div id="result" style="color: Green;"></div>


~/Home/testPartial.cshtml -> partial we will display after form submission



@model MvcApplication1.Models.testModel1
@{
    ViewBag.Title = "testPartial";
}

<h2>testPartial</h2>

<table>
        <tr>
            <td>
                First Name:
            </td>
            <td>
                @Html.DisplayFor(m => m.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                Last Name:
            </td>
            <td>
                @Html.DisplayFor(m => m.LastName)
            </td>
        </tr>
    </table>

~/Shared/_Layout.cshtml



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>

<body>
    @RenderBody()
</body>
</html>

TestCreate Page:


TestCreate Page After entering data:


TestCreate Page After submitting:


TestCreate Page After submit:


Note: don't miss the reference to "jquery.unobtrusive-ajax.min.js" in your application.


That's it go through the above code use them as mentioned and you are ready to submit your forms just like that.


Feel free to comment..


Happy ???