Friday, 10 January 2014

Jquery Multiselect in MVC Razor

View:

The below view consists of the code for both edit and insert 


          <div class="field">
                @Html.LabelFor(model => model.ProviderInsuranceID.Qualifiers)
 
                @if (Model.ProviderInsuranceID.Id > 0)
                {
                      @*  Render this conduction during the Edit Mode *@
                      <select name="ProviderInsuranceID.Qualifiers" multiple="multiple" id="ProviderInsuranceID_Qualifiers">
                        @{
                            if (!string.IsNullOrWhiteSpace(Model.SelectedQualifiers))
                            {
                               
                                IEnumerable<string> selQul = Model.SelectedQualifiers.Split(',').Select(v => v.ToString());
                                foreach (var qualifiers in Model.QualifiersList)
                                {
                                    if (selQul.Contains(qualifiers.Value))
                                    {
                                        @:<option selected="selected" value="@qualifiers.Value">@qualifiers.Text</option>
                                    }
                                    else
                                    {
                                        @:<option  value="@qualifiers.Value">@qualifiers.Text</option>
                                    }
                                }
                            }
                         }
                        
                    </select>
                }
                else
                {
                        @*  Render this conduction during the Insert Mode *@
                      @Html.DropDownListFor(model => model.ProviderInsuranceID.Qualifiers, Model.QualifiersList, new { @multiple = "multiple" })
                }
 
                @Html.ValidationMessageFor(model => model.ProviderInsuranceID.Qualifiers)
                  
@*  needs to append the selected values to the hidden field in comma separated like (2,5,6)
this is because rendering the content out the form tag , when we click submit button we are 
unable to get the selected value in the controller . so we are saving the selected value in
the hidden field 
 *@

                @Html.HiddenFor(model => model.SelectedQualifiers)
                
            </div>
 
 
Script:
 
 
 <script type="text/javascript">
 
    $(function () {
 
        var $hidcallback = $("#SelectedQualifiers");

        $("#ProviderInsuranceID_Qualifiers").multiselect({
            click: function (event, ui) {
                $hidcallback.text(ui.value + ' ' + (ui.checked ? 'checked' : 'unchecked'));
                var inputs = $hidcallback.val();
                
               if (inputs == "") {
                    inputs += ui.value;
                }
                else {
                    inputs += "," + ui.value;
                }
 
                var selvalues = inputs.split(',');
                selvalues = unique(selvalues);
                if (ui.checked == false) {

                    selvalues = jQuery.grep(selvalues, function (value) {
                        return value != ui.value;
                    });
                }
                // adding selected items to hidden filed.
                 $hidcallback.val(selvalues);
             }
        });
     });
 
// removes duplicate number from the array.
 
  function unique(list) {
        var result = [];
        $.each(list, function (i, e) {
            if ($.inArray(e, result) == -1) result.push(e);
        });
        return result;
    }
 
 </script>
 
 
Refference URL:
 
http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/ 
 
 
 
 

Monday, 12 August 2013

Jquery autocomplete Token Input in MVC 4 Razor View

 
 HTML in View:
 
 @Html.EditorFor(model => model.Provider.SupervisingProviders)
 
  

JavaScript Section in View :

 
 
<script type="text/javascript"> 
 
 $(document).ready(function () { 
 
       $("#Provider_SupervisingProviders").tokenInput("@Url.Action("GetProviders","Provider")", {
            theme: "facebook",
            tokenLimit: 4,
            preventDuplicates: true,
            hintText: "Type in provider Name",
            queryParam: "ProviderName" 
  
            // needs to place this conduction in edit mode (i.e) wants to display data on page load
 
             @if (Model.Provider.Id > 0 && !string.IsNullOrWhiteSpace(Model.SupervisingProvidersData) )
            {
               @: ,prePopulate:  @Html.Raw(HttpUtility.HtmlDecode(Model.SupervisingProvidersData))
            }
            
      });
 
  }); 
</script> 
 
 

Controller :

This Method is called by Token Input for get values
[HttpGet]
public JsonResult GetProviders(string ProviderName)
{
   var providers = _masterServiceClient.GetProviders().Where(a => a.FirstName.ToUpper().Contains(ProviderName.ToUpper()) || a.LastName.ToUpper().Contains(ProviderName.ToUpper())).ToList();
 
   IEnumerable providerList = providers.Select(results => new { id = results.Id, name = results.FirstName + " " + results.LastName });
 
   return Json(providerList, JsonRequestBehavior.AllowGet);
 
}
 
In Add Form If we dont want any values to be selected by default, so we need to retun empty 
string
if (model.SupervisingProvidersData != null)
{
    model.SupervisingProvidersData = System.Web.Helpers.Json.Encode(model.SupervisingProvidersData);
}

Saving Selected Values in Add Form :

The Selected Attributes is saved in the text box Provider_SupervisingProviders in comma separated
format  like '2,5,6' and we can save these values directly into the database.

Displaying Saved Values in Edit Form:

 

string selectedSupervisingProviders= model.Provider.SupervisingProviders;
 
                /// get the selected Supervising Providers
if (!string.IsNullOrWhiteSpace(selectedSupervisingProviders))
{
    IEnumerable<int> SupervisingProvider = selectedSupervisingProviders.Split(',').Select(SupervisingProviders => int.Parse(SupervisingProviders));
    var provide = providers.Where(rec => SupervisingProvider.Contains(rec.Id));
    IEnumerable providerList = provide.Select(results => new { id = results.Id, name = results.FirstName + " " + results.LastName });
    model.SupervisingProvidersData = System.Web.Helpers.Json.Encode(providerList);
}


Download the Token Input form the location:


http://loopj.com/jquery-tokeninput/

Saturday, 21 January 2012

Customized Datalist with columns in MVC 3 RAZOR

Default Datlist control in ( nopCommerce ) MVC 3 Razor :

the default datalist in MVC 3 Razor:

<div class="home-page-category-grid">
        @(Html.DataList<CategoryModel>(Model, 3,
                @<div class="item-box">
                    <div class="category-item">
                        <h2 class="title">
                            <a href="@Url.RouteUrl("Category", new { categoryId = item.Id,
SeName=item.SeName })" title="@item.PictureModel.Title">
                                @item.Name</a>
                        </h2>
                    </div>
                </div>
            ))
    </div>

This can be customize by using foreach loop by placing the design in a html table.

@{
    //enters inside if conduction when model has categories greater than zero
    if (Model.Count > 0)
    {
        // initializing loop count
        int i = 0;
        int j=0;
        int colsize = 3;// Assigning columns per table
      
        @:<div style="margin-bottom: 15%;">
        @:<div class="home-page-category-grid">
      
        //gets all the Model  data into the _categories variable
        foreach (var _categories in Model)
        {
            if (i % colsize == 0)
            {
               @::<table>
               @:<tr>
             
            }
           
              //design that displays  categories items
           
            <td>
                <div class="item-box">
                        <div class="category-item">
                            <div class="picture">
                                <a href="@Url.RouteUrl("Category", new { categoryId = _categories.Id, SeName = _categories.SeName })" title="@_categories.PictureModel.Title">
                                    <img class="category-display-picture" alt="@_categories.PictureModel.AlternateText" src="@_categories.PictureModel.ImageUrl"
                                        title="@_categories.PictureModel.Title" /></a>
                                <div class="picture-title">
                                    <a href="@Url.RouteUrl("Category", new { categoryId = _categories.Id, SeName = _categories.SeName })" title="@_categories.PictureModel.Title">
                                        @_categories.Name</a>
                                </div>
                            </div>
                           
                        </div>
                </div>
            </td>
   
            //doesnot apply blue line image for the last td according to column size
            if (i != colsize - 1)
            {
             <td>
               <img src="../../Content/Images/etch/border.jpg"  alt="" />
             </td>
            }

              i++;//increaments loop count           
              j++//increaments loop count

            //enters inside when the loop count and column size equals.
            // for applying the closing tr and table tags and again reset i count to zero
            if (i == colsize || j== Model.Count-1)
            {
                @:</tr>
               @:</table>
               i = 0;// resets the count when equals to the column size
            }

         

        }
       
        @:</div>
        @:</div>
       
    }
   
}