Saturday, 23 November 2013

cheboxfor in mvc

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

namespace MvcApplication2.Models
{
    public class EMP
    {
        public List<checkboxes> checkbox { get; set; }
    }
    public class checkboxes
    {
        public Boolean Ischeck { get; set; }
        public int Value { get; set; }
        public string Text { get; set; }
    }
}
Controler

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

namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            EMP eMP = new EMP();
            List<checkboxes> Checkboxes = new List<checkboxes>();
            checkboxes checkboxe = new checkboxes();
            checkboxe.Ischeck = false;
            checkboxe.Text = "Siv";
            checkboxe.Value = 1;
            Checkboxes.Add(checkboxe);
            checkboxes checkboxe1 = new checkboxes();
            checkboxe1.Ischeck = false;
            checkboxe1.Text = "Sankar";
            checkboxe1.Value = 2;
            Checkboxes.Add(checkboxe1);
            checkboxes checkboxe2 = new checkboxes();
            checkboxe2.Ischeck = false;
            checkboxe2.Text = "Mahadev";
            checkboxe2.Value = 3;
            Checkboxes.Add(checkboxe2);
            eMP.checkbox = Checkboxes;
            return View(eMP);
        }
    [HttpPost]
        public string Index(EMP emp)
        {
            string s = string.Empty;
            for (int i = 0; i < emp.checkbox.Count(); i++)
                if (emp.checkbox[i].Ischeck)
                    s = s + emp.checkbox[i].Value;
            return s;
        }


    }
}
View
@model MvcApplication2.Models.EMP

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using(Html.BeginForm())
{
    for (int i = 0; i < Model.checkbox.Count; i++)
    {
    @Html.HiddenFor(m=>m.checkbox[i].Value)
    @Html.CheckBoxFor(m=>m.checkbox[i].Ischeck)
    @Html.DisplayFor(m => m.checkbox[i].Text)<br />
    }
    <input type="submit" value="Submit" />
}

No comments:

Post a Comment