Video file upload in mvc 3 using ajax - ajax

Hi I tried to save image path in my database and retrieve it to my view to display image using the code below. Which is running perfectly. My problem now is how can I save video file using ajax? I used ajax because I'm not only saving images but I also have different data to save. e.g Name,code,blurb,synopsis etc. Thank you in advance for helping me.
In my view:
<tr>
<td>
Poster Homepage
</td>
<td style>
<form id="file_upload" action="/Movies/UploadFiles" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
#*<div class="progressbar fileupload-progressbar">
</div>*#
<div id="file_name">
</div>
<div id="file_type">
</div>
<div id="file_size">
</div>
<div id="show_image"></div>
<span class="fileinput-button"><a href="javascript:void(0)" class="upload-image">
Upload image</a>
<input type="file" name="files[]" multiple id="file" />
</span>
</div>
</form>
</td>
</tr>
script
$(document).ready(function () {
$('.progressbar').progressbar({ value: 0 });
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
progressall: function (e, data) {
$(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
},
done: function (e, data) {
$('#file_name').html(data.result.name);
$('#file_type').html(data.result.type);
$('#file_size').html(data.result.size);
$('#show_image').html('<img src="/home/image/' + data.result.name + '" />');
$('#file_name').css({ display: 'none' });
$('#file_type').css({ display: 'none' });
$('#file_size').css({ display: 'none' });
//visibility: hidden;
$(this).find('.progressbar').progressbar({ value: 100 });
}
});
Controller:
public FilePathResult Image()
{
string filename = Request.Url.AbsolutePath.Replace("/home/image", "");
string contentType = "";
var filePath = new FileInfo(Server.MapPath("~/Images") + filename);
var index = filename.LastIndexOf(".") + 1;
var extension = filename.Substring(index).ToUpperInvariant();
// Fix for IE not handling jpg image types
contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);
return File(filePath.FullName, contentType);
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadHomePage>();
foreach (string file in Request.Files)
{
HttpPostedFileBase image = Request.Files[file] as HttpPostedFileBase;
if (image.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
image.SaveAs(savedFileName);
r.Add(new UploadHomePage()
{
Name = image.FileName,
Length = image.ContentLength,
Type = image.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookingCMS.Models
{
public class UploadHomePage
{
public string Name { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
}

You could pass additional parameters with the FileUpload plugin using the formData setting:
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
formData : {
name: 'this is the name of the movie',
synopsis: 'this is the synopsis of the movie',
type: 'movie'
},
progressall: function (e, data) {
...
},
done: function (e, data) {
...
}
});

Related

Aspnet Core - Error 400 When i send Httpost with js

I need to get a list permissao when I select a group, I made the methods but when I select the group, it returns me an error.
PermissaoGrupo/ObterPermissoesAdd:1 Failed to load resource: the
server responded with a status of 400 ()
View
#model RKMES.Models.ViewModel.PermissaoGrupoViewModel
<script type="text/javascript" src="assets/js/plugins/forms/inputs/duallistbox.min.js"></script>
<script type="text/javascript" src="assets/js/pages/form_dual_listboxes.js"></script>
<h2>Index</h2>
<div class="form-group">
#*<label asp-for="Grupos" class="control-label">Grupo</label>*#
#*<select class="custom-select custom-select-sm" asp-items="#(new SelectList(Model.Grupos,"Id","Nome"))"></select>*#
Grupos
#Html.DropDownList("Grupos", new SelectList(Model.Grupos,"Id", "Nome"))
</div>
<!-- Filtered results -->
<div class="panel panel-flat">
<div class="panel-heading">
<h5 class="panel-title">Filtered results</h5>
</div>
<div class="panel-body">
#*<select multiple="multiple" class="form-control listbox-no-selection" asp-items="#(new SelectList(Model.Permissoes,"Id","Nome"))"></select>*#
#Html.DropDownList("Permissoes", new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Nome"))
</div>
</div>
<!-- /filtered results -->
<script type="text/javascript">
$(document).ready(function () {
$('#Grupos').change(function () {
var idGrupo = $('#Grupos').val();
if (idGrupo > 0) {
$.post('#Url.Action("ObterPermissoesAdd", "PermissaoGrupo")', { 'idGrupo': idGrupo }, function (data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$('#Permissoes').append('<option value="' +data[i].Id+ '">' + data[i].Nome+ '</option>');
}
}
});
}
});
});
</script>
PermissaoGrupoController
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ObterPermissoesAdd(int idGrupo)
{
return Json(_grupoContext.GetPermissoesAdd(idGrupo));
}
GrupoService
public async Task<List<Permissao>> GetPermissoesAdd(int id)
{
return await _context.Grupo_Permissao_Permissao
.Where(x => x.Grupo_PermissaoId == id)
.Select(x => x.Permissao)
.ToListAsync();
}
Model
namespace RKMES.Models
{ // essa é uma tabela intermediaria das entidades Grupo_Permissao e Permissao
public class Grupo_Permissao_Permissao
{
public int Id { get; set; }
public int Grupo_PermissaoId { get; set; }
public int PermissaoId { get; set; }
public virtual Grupo_Permissao Grupo_Permissao { get; set; }
public virtual Permissao Permissao { get; set; }
}
}
What am I doing wrong?
For your issue, it is caused by ValidateAntiForgeryToken. which will check whether the request contains RequestVerificationToken header.
For a quick test, you could remove [ValidateAntiForgeryToken] from Controller.
For a recommended way, you need to attach the anti forgery token like
<script type="text/javascript">
$(document).ready(function(){
var Group = {
GroupId: 1,
GroupName: "My Group Name"
};
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
headers: {
"RequestVerificationToken": gettoken()
},
data: JSON.stringify(data)
});
}
</script>

update model with ajax in razor

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have masterpage.in picture u see what happen.
this is my code
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
<div class="btnContainer">
delete
<br />
<br />
</div>
<script>
$(function () {
// function for delet info and update #updateAjax div
$("#DeleteUser").click(function (event) {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
$.ajax({
url: '#Url.Action("DeleteUser", "UserManagement")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: JSON.stringify(list),
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
// window.location.reload()
},
error: function (data) {
//$('#updateAjax').html(data);
window.location.reload()
}
}); //end ajax
});});
</script>
</form>
this my controller code
public ActionResult View1()
{
ViewBag.PageTittle = "user list";
ViewBag.FormTittle = "user list";
SetUserManagement();
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(Result.Data);
}
else
{
return View(new VwUser());
}
}
public ActionResult DeleteUser(string[] userId)
{
SetUserManagement();
string message = "", CssClass = ""; ;
foreach (string item in userId)
{
//TODO:show Message
var Result = userManagement.DeleteUser(int.Parse(item));
if (Result.Mode != Common.Extensions.ActionResultMode.Successfully)
{
var messageResult = XmlReader.FindMessagekey(Result.Mode.ToString());
message += messageResult.MessageContent + "<br/>";
CssClass = messageResult.cssClass;
}
}
if (string.IsNullOrEmpty(message))
{
SetMessage(Common.Extensions.ActionResultMode.Successfully.ToString());
}
else
{
ViewBag.MessageResult = message;
ViewBag.cssClass = CssClass;
}
//
{
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View("~/Views/UserManagement/View1.cshtml", Result.Data);
}
else
{
return View("~/Views/UserManagement/View1.cshtml", new VwUser());
}
}
}
It looks to me that your view ViewUserList.cshtml is using a Layout that would either be set through Layout or through the _ViewStart.cshtml file. Make sure you're not using any of these.
For disabling the use of your Layout, you could take a look at this question. Or just set Layout = null

Uploading/Displaying Images in MVC 4

Anyone know of any step by step tutorials on how to upload/display images from a database using Entity Framework? I've checked out code snippets, but I'm still not clear on how it works. I have no code, because aside from writing an upload form, I'm lost. Any (and I mean any) help is greatly appreciated.
On a sidenote, why don't any books cover this topic? I have both Pro ASP.NET MVC 4 and Professional MVC4, and they make no mention of it.
Have a look at the following
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
your controller should have action method which would accept HttpPostedFileBase;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
Update 1
In case you want to upload files using jQuery with asynchornously, then try this article.
the code to handle the server side (for multiple upload) is;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.
UPDATE 2
Alternatively, you can try Async File Uploads in MVC 4.
Here is a short tutorial:
Model:
namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;
public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}
View:
Create:
#model ImageUploadApp.Models.Image
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Index (for display):
#model IEnumerable<ImageUploadApp.Models.Image>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
</td>
</tr>
}
</table>
Controller (Create)
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Image.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
Hope this will help :)
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}

ASP.NET MVC3: Ajax postback doesnot post complete data from the view

Hi Greetings for the day!
(1) The view model (MyViewModel.cs) which is bound to the view is as below...
public class MyViewModel
{
public int ParentId { get; set; } //property1
List<Item> ItemList {get; set;} //property2
public MyViewModel() //Constructor
{
ItemList=new List<Item>(); //creating an empty list of items
}
}
(2) I am calling an action method through ajax postback (from MyView.cshtml view) as below..
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {$('#MyForm').html(html);}
});
}
The below button click will call the ajax postback...
<input type="button" value="Add" class="Previousbtn" onclick="AddItem()" />
(3) I have an action method in the (MyController.cs controller) as below...
public ActionResult AddItem(MyViewModel ViewModel)
{
ViewModel.ItemList.Add(new Item());
return View("MyView", ViewModel);
}
Now the issue is, after returning from the action, there is no data in the viewmodel. But i am able to get the data on third postback !! Can you pls suggest the solution..
The complete form code in the view is below...
#model MyViewModel
<script type="text/javascript" language="javascript">
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function RemoveItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/RemoveItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function SaveItems() {
var form = $('#MyForm');
var serializedform = forModel.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/SaveItems")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
</script>
#using (Html.BeginForm("SaveItems", "MyController", FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(m => Model.ParentId)
<div>
<input type="button" value="Save" onclick="SaveItems()" />
</div>
<div>
<table>
<tr>
<td style="width: 48%;">
<div style="height: 500px; width: 100%; overflow: auto">
<table>
<thead>
<tr>
<th style="width: 80%;">
Item
</th>
<th style="width: 10%">
Select
</th>
</tr>
</thead>
#for (int i = 0; i < Model.ItemList.Count; i++)
{
#Html.HiddenFor(m => Model.ItemList[i].ItemId)
#Html.HiddenFor(m => Model.ItemList[i].ItemName)
<tr>
#if (Model.ItemList[i].ItemId > 0)
{
<td style="width: 80%; background-color:gray;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%; background-color:gray;">
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
#Html.HiddenFor(m => Model.ItemList[i].IsSelected)
</td>
}
else
{
<td style="width: 80%;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%">
#if ((Model.ItemList[i].IsSelected != null) && (Model.ItemList[i].IsSelected != false))
{
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
}
else
{
#Html.CheckBoxFor(m => Model.ItemList[i].IsSelected, new { #style = "cursor:pointer" })
}
</td>
}
</tr>
}
</table>
</div>
</td>
<td style="width: 4%; vertical-align: middle">
<input type="button" value="Add" onclick="AddItem()" />
<input type="button" value="Remove" onclick="RemoveItem()" />
</td>
</tr>
</table>
</div>
}
You must return PartialViewResult and then you can do something like
$.post('/controller/GetMyPartial',function(html){
$('elem').html(html);});
[HttpPost]
public PartialViewResult GetMyPartial(string id
{
return PartialView('view.cshtml',Model);
}
In my project i get state data with country id using json like this
in my view
<script type="text/javascript">
function cascadingdropdown() {
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
alert(data);
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
in my controller return data in json format
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
i think this will help you ....
I resolved the issue as below...
Issue:
The form code i have shown here is actually part of another view page
which also contains a form. So, when i saw the page source at
run-time, there are two form tags: one inside the other, and the
browser has ignored the inner form tag.
Solution:
In the parent view page, earlier i had used Html.Partial to render
this view by passing the model to it.
#using(Html.BeginForm())
{
---
---
#Html.Partial('/MyArea/Views/MyView',MyViewModel)
---
---
}
But now, i added a div with no content. On click of a button, i'm
calling an action method (through ajax postback) which then renders
the above shown view page (MyView.cshmtl) into this empty div.
#using(Html.BeginForm())
{
---
---
<div id="divMyView" style="display:none"></div>
---
---
}
That action returns a separate view which is loaded into the above
div. Since it is a separate view with its own form tag, i'm able to
send and receive data on each postback.
Thank you all for your suggestions on this :)

How to pass combination of Id-date to Controller from View in MVC3

In my HTML table I have a checkbox, start and end date
I have set checkbox's id as primary kay of that record/row
on click of checkbox, the corresponding record's end date text box is bound to a datepicker through which date can b changed
I can do this for multiple records in my table
at the end I have a button , on click of it I want to send this selected rows id and its edited end date value to the controller
through out my code i'm able to do this but the problem is that only last updated value is sent to the controller and not all the values
Here is my code :
<div class="cell" style="width:auto;">
<input type="checkbox" name="chkbox" class="a" value="" data-id="#item.ID" onclick="checkbox1(#item.ID)"/>
</div>
<div class="cell" style="width:auto;">
#Html.DisplayFor(modelItem => item.StartDate, new { id = "strtDate" })
</div>
<div class="cell" id="edit2-#item.ID" style="width:auto;">
#Html.DisplayFor(modelItem => item.EndDate, new { id = "endDate" })
</div>
<div class="cell" id="edit1-#item.ID" style="width:auto; display:none;">
#Html.TextBox("Enddate", item.EndDate, new { #class = "date", id = "date-" + #item.ID })
</div>
I'm hiding div edit2-#itemID and showing edit1-#itemID on click of checkbox and also binding datepicker to it
function checkbox1(index) {
var divname =index;
$("#edit1-" + divname).toggle();
$("#edit2-" + divname).toggle();
$("#date-" + divname).datepicker({ yearRange: "-0:+13",
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mm-yy',
onSelect: function (dateText, inst) {
var test = dateText + "," + divname;
alert(test);
$(".a:checked").attr('data-id', test);
}
});
}
I tried to set the checkbox's id as combination of "id-newenddate"
but it is assigning the recent date to all selected checkboxes.
Following is the code called wen button is clicked
$("#button1").click(function () {
var selected = $(".a:checked").map(function () {
return $(this).data('id');
}).get();
var urlDistricts = '#Url.Action("EditExhi")';
$.ajax({
type: "POST",
datatype: 'integer',
url: urlDistricts,
traditional: true,
data: { listofid: selected},
success: function (result) {
}
});
in controller:
[HttpPost]
public ActionResult EditExhi(List<int> listofid)
{
}
How can I solve this issue and send the combination of id-date to controller?
Please help me.
You need to be able to match the checkboxes with the items:
Add an index to your view model:
public class YourViewModel
{
public int Index {get;set;}
public IEnumerable<YourItemType> Items {get; set; }
// other fields
}
And use it in the view:
#foreach(var item in Model.Items)
{
<div class="cell" style="width:auto;">
<input type="checkbox" name="chkbox[#Model.Index]" class="a" value="true" data-id="#item.ID" onclick="checkbox1(#item.ID)"/>
</div>
<div class="cell" style="width:auto;">
#Html.DisplayFor(modelItem => item.StartDate, new { id = "strtDate" })
</div>
<div class="cell" id="edit2-#item.ID" style="width:auto;">
#Html.DisplayFor(modelItem => item.EndDate, new { id = "endDate" })
</div>
<div class="cell" id="edit1-#item.ID" style="width:auto; display:none;">
#Html.TextBox("Enddate[" + Model.Index + "]", item.EndDate, new { #class = "date", id = "date-" + #item.ID })
</div>
<input type="hidden" name="Id[#Model.Index]" value="#item.ID" />
#{Model.Index = #Model.Index + 1}
}
Then create a new view model for the post action:
public class PostModel
{
bool chkbox { get; set; }
string EndDate {get;set; }
string Id { get; set; }
}
then do this in the action:
[HttpPost]
public ActionResult EditExhi(PostModel[] items)
{
foreach (var item in items)
{
if (item.chkbox)
//update db here with item.EndDate & item.Id
}
}

Resources