A day with .Net

My day to day experince in .net

Archive for February, 2014

Passing all the values (including unselected) of a list box to MVC controller.

Posted by vivekcek on February 26, 2014

In normal case when we submit form only the selected values of the listbox is bind to model.
If you want to get all the values of the listbox on post. Try the blow tip.

Add the below jquery function, which select all the list box items before submit.

<script type="text/javascript">
    $(document).ready(function () {

        $("#myForm").submit(function (e) {

            $("#myList option").prop("selected", "selected");

        });

    });
</script>

Complete solution is given below.

1. Define the model.

public class MyViewModel
    {
        public string[] SelectedValues { get; set; }
        public List<SelectListItem> Items { get; set; }
    }

2. Define the controller

 public ActionResult Index()
        {
            MyViewModel m = new MyViewModel()
            {
                Items = new List<SelectListItem>() 
             {
                new SelectListItem { Value = "1", Text = "item 1" },
                new SelectListItem { Value = "2", Text = "item 2" },
                new SelectListItem { Value = "3", Text = "item 3" },
                new SelectListItem { Value = "4", Text = "item 4" },
             }
            };

            return View(m);
        }

        public ActionResult GetResult(MyViewModel model)
        {
            return RedirectToAction("Index");
        }

3. Define the view

@model MvcListBox.Models.MyViewModel

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("GetResult", "Home", FormMethod.Post, new { id = "myForm" }))
{

    @Html.ListBoxFor(m => m.SelectedValues, Model.Items, new { id = "myList" })
    <button type="submit">Submit</button>
}

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    $(document).ready(function () {

        $("#myForm").submit(function (e) {

            $("#myList option").prop("selected", "selected");

        });

    });
</script>
Advertisements

Posted in MVC | 1 Comment »

MVC Sending Listbox selected values to controller – Code Snippet

Posted by vivekcek on February 25, 2014

1. Define model

 public class MyViewModel
    {
        public string[] SelectedValues { get; set; }
        public List<SelectListItem> Items { get; set; }
    }

2. Define controller

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            MyViewModel m = new MyViewModel()
            {
                Items = new List<SelectListItem>() 
             {
                new SelectListItem { Value = "1", Text = "item 1" },
                new SelectListItem { Value = "2", Text = "item 2" },
                new SelectListItem { Value = "3", Text = "item 3" },
                new SelectListItem { Value = "4", Text = "item 4" },
             }
            };

            return View(m);
        }

        public ActionResult GetResult(string[] Values)
        {
            return Json(new { message = string.Format("Number of values {0}", Values.Length) }, JsonRequestBehavior.AllowGet);
        }
    }

3. Define View

@model MvcListBox.Models.MyViewModel

@{
    ViewBag.Title = "Home Page";
}

@Html.ListBoxFor(m => m.SelectedValues, Model.Items, new { id = "myList" })
@Html.ActionLink("My Action", "GetResult", null, new { id = "myLink" })

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    $(document).ready(function () {

        $("#myLink").click(function () {

            var selectedValues = $('#myList').val();
            $.getJSON(this.href, $.param({ values: selectedValues }, true), function (result) {
                alert(result.message);
            });
            return false;
        });

    });
</script>

Posted in MVC | Leave a Comment »

How to implement a dropdownlist in MVC.

Posted by vivekcek on February 25, 2014

1. Create a viewmodel class as below.

public class AddProductViewModel
    {

        [Display(Name="Category")]
        public string CategoryId { get; set; }

        public List<SelectListItem> Categories { get; set; }
    }

2. Create the controller as below.

public class ProductController : Controller
    {
        
        [HttpGet]
        public ActionResult AddProduct()
        {
            AddProductViewModel model = new AddProductViewModel();
            List<SelectListItem> categories = new List<SelectListItem> {
            new SelectListItem{  Value="1",   Text="First"},
            new SelectListItem{  Value="2",   Text="Second"},
            };
            model.Categories = categories;
            return View(model);
        }

        [HttpPost]
        public ActionResult AddProduct(AddProductViewModel model)
        {
            return RedirectToAction("AddProduct");
        }

    }

3. Create a View

@model AAElectronics.ViewModel.AddProductViewModel
@{
    ViewBag.Title = "AddProduct";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AddProduct</h2>


@using (Html.BeginForm("AddProduct", "Product", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div>
        @Html.DropDownListFor(m => m.CategoryId, Model.Categories, "-Select-")
    </div>
   
    <button type="submit">Create</button>
}

The category Id will contain the selected item id

Posted in MVC | Leave a Comment »