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" />
}

Tuesday, 19 November 2013

File upload in mvc

Uploading a single file

Let’s start with the view. Here’s a form that will post back to the current action.
<form action="" method="post" enctype="multipart/form-data">
  
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>
Here’s the action method that this view will post to which saves the file into a directory in the App_Data folder named “uploads”.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
            
  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }
            
  return RedirectToAction("Index");
}

c# link