MVC; How do you avoid ID name collisions when using tabs? - asp.net-mvc

There is a lot to commend MVC, but one problem I keep getting is ID name collisions.
I first noticed it when generating a grid using a foreach loop. With the help of SO I found the solution was to use Editor Templates.
Now I have the same problem with tabs.
I used this reference to find out how to use tabs; http://blog.roonga.com.au/search?updated-max=2010-06-14T19:27:00%2B10:00&max-results=1
The problem with my tabs is that I am using a date field with a date picker. In the example above, ID name collisions are avoided by referencing a generated unique Id of the container element. However for a datepicker, the ID of the container is irrelevant, only the ID of the date field matters. So what happens is that if I create my second tab the same as the first, when I update my second tab, the date on the first is updated.
So below is my View, and a partial view which displays the date. When I click the "Add Absence for 1 day button, I create a tab for that screen;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master"
Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.AbsenceViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
AbsenceForEmployee
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">
<script type="text/javascript">
$(function () {
$('#tabs').tabs(
{ cache: true },
{
ajaxOptions: {
cache: false,
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("Couldn't load this tab.");
},
data: {},
success: function (data, textStatus) { }
},
add: function (event, ui) {
//select the new tab
$('#tabs').tabs('select', '#' + ui.panel.id);
}
});
});
function addTab(title, uri) {
var newTab = $("#tabs").tabs("add", uri, title);
}
function closeTab() {
var index = getSelectedTabIndex();
$("#tabs").tabs("remove", index)
}
function getSelectedTabIndex() {
return $("#tabs").tabs('option', 'selected');
}
function RefreshList() {
$('#frmAbsenceList').submit();
}
</script>
<% using (Html.BeginForm()) {%>
<%: Html.AntiForgeryToken() %>
<fieldset>
<legend>Select an employee to edit absence record</legend>
<div style="padding-bottom:30px;padding-left:10px;">
<div class="span-7"><b>Name:</b> <%: Model.Employee.GetName() %></div>
<div class="span-6"><b>Division:</b><%: Model.DivisionName %></div>
<div class="span-6"><b>Department:</b> <%: Model.DepartmentName %></div></div>
<p>Attendance record for the year <%: Html.DropDownListFor(model => model.SelectedYearId, Model.YearList, new { onchange = "this.form.submit();" })%></p>
<div id="tabs">
<ul>
<li>Absence List</li>
</ul>
<div id="tabs-1">
<input id="btnAddOneDayTab" type="button" onclick="addTab('Add Absence (1 day)','<%= Url.Action("AddAbsenceOneDay", "Employee") %>')" value='Add Absence for 1 day' />
<input id="btnAddDateRangeTab" type="button" onclick="addTab('Add Absence (date range)','<%= Url.Action("AddAbsenceDateRange", "Employee") %>')" value='Add Absence for a range of dates' />
<hr />
<% Html.RenderPartial("ListAbsence", Model.ListEmployeeAbsenceThisYear); %>
</div>
</div>
</fieldset>
<% } %>
Add new date partial view ...
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.EmployeeOtherLeaf>" %>
<% var unique = DateTime.Now.Ticks.ToString(); %>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#frmAddAbsenceOneDay<%= unique %> #NullableOtherLeaveDate').datepicker({ dateFormat: 'dd-MM-yy' });
$('#frmAddAbsenceOneDay<%= unique %> #MorningOnlyFlag').click(function () {
$('#frmAddAbsenceOneDay<%= unique %> #AfternoonOnlyFlag').attr('checked', false);
})
$('#frmAddAbsenceOneDay<%= unique %> #AfternoonOnlyFlag').click(function () {
$('#frmAddAbsenceOneDay<%= unique %> #MorningOnlyFlag').attr('checked', false);
})
});
var options = {
target: '#frmAddAbsenceOneDay<%= unique %>',
success: RefreshList
};
$(document).ready(function () {
$('#frmAddAbsenceOneDay<%= unique %>').ajaxForm(options);
});
</script>
<div id="AddAbsenceOnDay<%= unique %>">
<% using (Html.BeginForm("AddAbsenceOneDay", "Employee", FormMethod.Post,
new { id = "frmAddAbsenceOneDay" + unique }))
{ %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Add an absence for a day or half day</legend>
<table>
<tr>
<td><%: Html.LabelFor(model => model.OtherLeaveId)%></td>
<td>
<%: Html.DropDownListFor(model => model.OtherLeaveId, Model.SelectLeaveTypeList, "<--Select-->")%>
<%: Html.ValidationMessageFor(model => model.OtherLeaveId)%>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(model => model.NullableOtherLeaveDate)%>
</td>
<td>
<%: Html.EditorFor(model => model.NullableOtherLeaveDate)%>
<%: Html.ValidationMessageFor(model => model.NullableOtherLeaveDate)%>
<%if (ViewData["ErrorDateMessage"] != null && ViewData["ErrorDateMessage"].ToString().Length > 0)
{ %>
<p class="error">
At <% Response.Write(DateTime.Now.ToString("T")); %>. <%: ViewData["ErrorDateMessage"]%>.
</p>
<%} %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(model => model.MorningOnlyFlag)%>
</td>
<td>
<%: Html.CheckBoxFor(model => model.MorningOnlyFlag)%>
<%: Html.ValidationMessageFor(model => model.MorningOnlyFlag)%>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(model => model.AfternoonOnlyFlag)%>
</td>
<td>
<%: Html.CheckBoxFor(model => model.AfternoonOnlyFlag)%>
<%: Html.ValidationMessageFor(model => model.AfternoonOnlyFlag)%>
</td>
</tr>
</table>
<p>
<span style="padding-right:10px;"><input type="submit" value="Create" /></span><input type="button" value="Close" onclick="closeTab()" />
</p>
</fieldset>
<% } %>
</div>
You can see the ID of the date in the following HTML from Firebug
<div id="main">
<div id="adminAccounts">
<table>
<tbody><tr>
<td>
<div style="padding-top: 15px;">
// Menu removed
</div>
</td>
<td>
<script type="text/javascript">
$(function () {
$('#tabs').tabs(
{ cache: true },
{
ajaxOptions: {
cache: false,
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("Couldn't load this tab.");
},
data: {},
success: function (data, textStatus) { }
},
add: function (event, ui) {
//select the new tab
$('#tabs').tabs('select', '#' + ui.panel.id);
}
});
});
function addTab(title, uri) {
var newTab = $("#tabs").tabs("add", uri, title);
}
function closeTab() {
var index = getSelectedTabIndex();
$("#tabs").tabs("remove", index)
}
function getSelectedTabIndex() {
return $("#tabs").tabs('option', 'selected');
}
function RefreshList() {
$('#frmAbsenceList').submit();
}
</script>
<form method="post" action="/Employee/AbsenceForEmployee?employeeId=1"><input type="hidden" value="8yGn2w+fgqSRsho/d+7FMnPWBtTbu96X4u1t/Jf6+4nDSNJHOPeq7IT9CedAjrZIAK/DgbNX6idtTd94XUBM5w==" name="__RequestVerificationToken">
<fieldset>
<legend>Select an employee to edit absence record</legend>
<div style="padding-bottom: 30px; padding-left: 10px;">
<div class="span-7"><b>Name:</b> xaviar caviar</div>
<div class="span-6"><b>Division:</b>ICT</div>
<div class="span-6"><b>Department:</b> ICT</div></div>
<p>Absence Leave record for the year <select onchange="this.form.submit();" name="SelectedYearId" id="SelectedYearId"><option value="2" selected="selected">2010/11</option>
</select></p>
<div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
<li class="ui-state-default ui-corner-top">Absence List</li>
<li class="ui-state-default ui-corner-top"><span>Add Absence (1 day)</span></li><li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><span>Add Absence (1 day)</span></li></ul>
<div id="tabs-1" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide">
<input type="button" value="Add Absence for 1 day" onclick="addTab('Add Absence (1 day)','/Employee/AddAbsenceOneDay')" id="btnAddOneDayTab">
<input type="button" value="Add Absence for a range of dates" onclick="addTab('Add Absence (date range)','/Employee/AddAbsenceDateRange')" id="btnAddDateRangeTab">
<hr>
<script type="text/javascript">
var options = {
target: '#AbsenceList'
};
$(document).ready(function() {
$('#frmAbsenceList').ajaxForm(options);
});
</script>
<div id="AbsenceList">
<table class="grid"><thead><tr><th class="sort_asc"></th><th>Leave Type</th><th>Morning Only</th><th>Afternoon Only</th><th>Day Amount</th><th>Date</th></tr></thead><tbody><tr class="gridrow"><td>Delete</td><td>Sickness</td><td>False</td><td>False</td><td>1</td><td>04/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>08/11/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Unpaid Compassionate</td><td>False</td><td>False</td><td>1</td><td>09/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>10/11/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>15/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>16/11/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>17/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>22/11/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>24/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Sickness</td><td>False</td><td>False</td><td>1</td><td>25/11/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>26/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>29/11/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>30/11/2010</td></tr><tr class="gridrow_alternate"><td>Delete</td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>13/12/2010</td></tr><tr class="gridrow"><td>Delete</td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>26/12/2010</td></tr></tbody></table>
<p></p><div class="pagination"><span class="paginationLeft">Showing 1 - 15 of 21 </span><span class="paginationRight">first | prev | next | last</span></div>
</div>
</div><div id="ui-tabs-2" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide">
<div id="AddAbsenceOnDay634255177533718544">
<form method="post" id="frmAddAbsenceOneDay634255177533718544" action="/Employee/AddAbsenceOneDay">
<fieldset>
<legend>Add an absence for a day or half day</legend>
<table>
<tbody><tr>
<td><label for="OtherLeaveId">Leave Type</label></td>
<td>
<select name="OtherLeaveId" id="OtherLeaveId"><option value=""><--Select--></option>
<option value="1">Sickness</option>
<option value="2">Unpaid Sickness</option>
<option value="6">Compassionate</option>
<option value="7">Unpaid Compassionate</option>
<option value="8">Unauthorised</option>
<option value="9">Unpaid Unauthorised</option>
<option value="10">Other</option>
<option value="11">Unpaid Other</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="NullableOtherLeaveDate">Date</label>
</td>
<td>
<input type="text" value="" name="NullableOtherLeaveDate" id="NullableOtherLeaveDate" class="datePicker hasDatepicker">
</td>
</tr>
<tr>
<td>
<label for="MorningOnlyFlag">Morning Only</label>
</td>
<td>
<input type="checkbox" value="true" name="MorningOnlyFlag" id="MorningOnlyFlag"><input type="hidden" value="false" name="MorningOnlyFlag">
</td>
</tr>
<tr>
<td>
<label for="AfternoonOnlyFlag">Afternoon Only</label>
</td>
<td>
<input type="checkbox" value="true" name="AfternoonOnlyFlag" id="AfternoonOnlyFlag"><input type="hidden" value="false" name="AfternoonOnlyFlag">
</td>
</tr>
</tbody></table>
<p>
<span style="padding-right: 10px;"><input type="submit" value="Create"></span><input type="button" onclick="closeTab()" value="Close">
</p>
</fieldset>
</form>
</div>
</div><div id="ui-tabs-4" class="ui-tabs-panel ui-widget-content ui-corner-bottom">
<div id="AddAbsenceOnDay634255177583860349">
<form method="post" id="frmAddAbsenceOneDay634255177583860349" action="/Employee/AddAbsenceOneDay">
<fieldset>
<legend>Add an absence for a day or half day</legend>
<table>
<tbody><tr>
<td><label for="OtherLeaveId">Leave Type</label></td>
<td>
<select name="OtherLeaveId" id="OtherLeaveId"><option value=""><--Select--></option>
<option value="1">Sickness</option>
<option value="2">Unpaid Sickness</option>
<option value="6">Compassionate</option>
<option value="7">Unpaid Compassionate</option>
<option value="8">Unauthorised</option>
<option value="9">Unpaid Unauthorised</option>
<option value="10">Other</option>
<option value="11">Unpaid Other</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="NullableOtherLeaveDate">Date</label>
</td>
<td>
<input type="text" value="" name="NullableOtherLeaveDate" id="NullableOtherLeaveDate" class="datePicker hasDatepicker">
</td>
</tr>
<tr>
<td>
<label for="MorningOnlyFlag">Morning Only</label>
</td>
<td>
<input type="checkbox" value="true" name="MorningOnlyFlag" id="MorningOnlyFlag"><input type="hidden" value="false" name="MorningOnlyFlag">
</td>
</tr>
<tr>
<td>
<label for="AfternoonOnlyFlag">Afternoon Only</label>
</td>
<td>
<input type="checkbox" value="true" name="AfternoonOnlyFlag" id="AfternoonOnlyFlag"><input type="hidden" value="false" name="AfternoonOnlyFlag">
</td>
</tr>
</tbody></table>
<p>
<span style="padding-right: 10px;"><input type="submit" value="Create"></span><input type="button" onclick="closeTab()" value="Close">
</p>
</fieldset>
</form>
</div>
</div>
<div id="ui-tabs-1" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"></div><div id="ui-tabs-3" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"></div></div>
</fieldset>
</form></td>
</tr>
</tbody></table></div>
<div id="footer">
</div>
</div>
If you have got this far(!), I have been asked for the controller, so here it is.
[Authorize(Roles = "Administrator, AdminAccounts, ManagerAccounts")]
public ActionResult AddAbsenceOneDay()
{
return View(new EmployeeOtherLeaf());
}
[HttpPost]
[Authorize(Roles = "Administrator, AdminAccounts, ManagerAccounts")]
public ActionResult AddAbsenceOneDay(EmployeeOtherLeaf _absence)
{
if (ModelState.IsValid)
{
_absence.EmployeeId = SessionObjects.EmployeeId;
_absence.OtherLeaveDate = _absence.NullableOtherLeaveDate.GetValueOrDefault(DateTime.Today);
Tuple<bool, string> errorInfo = _absence.IsDateValid();
if (errorInfo.Item1 == true)
{
_absence.AddAndSave();
ViewData["SuccessMessage"] = "Successfully Added.";
return View("EditAbsenceOneDay", _absence);
}
else
{
ViewData["ErrorDateMessage"] = errorInfo.Item2;
return View(_absence);
}
}
else
{
return View(_absence);
}
}

The problem seems to be that the DOM only has one entry for NullableOtherLeaveDate. This seems logical because of the use of ID. What you can to is add the hash to the ID as well. If you need to match that ID with any jQuery you can use partial selectors like this:
$('input[id*=NullableOtherLeaveDate]')
See jQuery Partial Selectors for more about that.
Now how the modal binder will bind that I'm not sure but you can probably implement partial matching in C# with no problems. If you want any help with this please post the relevant code of your action.

The answer to this other question suggests using editor templates instead of partials to solve the problem.
MVC - fields in a partial View need a Unique Id. How do you do this?
Of course this will not work for every situations, just the editor ones.
Update:
There is another easy way too. The ViewData has a nice property you can use to set a prefix that makes the partial unique, then this ViewDataDictonary can be passed to the partial.
var dataDictionary = new ViewDataDictionary<PersonModel>(Model.Persons.First);
dataDictionary.TemplateInfo.HtmlFieldPrefix = "Persons.First";
See the following links for details on this:
- http://forums.asp.net/t/1627585.aspx/1
- http://forums.asp.net/t/1624152.aspx
Notice this overload of Html.Partial():
Partial(HtmlHelper, String, Object, ViewDataDictionary)
http://msdn.microsoft.com/en-us/library/ee407417.aspx

Related

How to Save records to Master-detail tables in ASP.NET MVC 5

I have Test and Deta(Details) table in DB. With Entity Framework 5 I have obtained a model so I have classes generated from it. I also created controllers and views for the Deta table. I can add, clear and delete the records before saving but finally, I can't to save the records.
Test table has
(TestID,
MissionCode,
StartDate,
EndDate)
Deta table has
(DetaId,
TestType,
TestDate,
Driver,
Place,
TestID)
I used the following script in the view to add, clear and save the record.
#section scripts{
<script>
//Show Modal.
function addNewDeta() {
$("#newDetaModal").modal();
}
//Add Multiple Order.
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#testType").val()) == "" || $.trim($("#testDate").val()) == "" || $.trim($("#driver").val()) == "" || $.trim($("#place").val()) == "") return;
var testType = $("#testType").val(),
testDate = $("#testDate").val(),
driver = $("#driver").val(),
place = $("#place").val(),
detailsTableBody = $("#detailsTable tbody");
var tstItem = '<tr><td>' + testType + '</td><td>' + testDate + '</td><td>' + driver + '</td><td>' + place + '</td><td><a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(tstItem);
clearItem();
});
//After Add A New Order In The List, Clear Clean The Form For Add More Order.
function clearItem() {
$("#testType").val('');
$("#testDate").val('');
$("#driver").val('');
$("#place").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove It.
$(document).on('click', 'a.deleteItem', function (e) {
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "#ff6347").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveDeta(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Detas/SaveDeta",
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveDeta").click(function (e) {
e.preventDefault();
var detaArr = [];
detaArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
detaArr.push({
testType: $(this).find('td:eq(0)').html(),
testDate: $(this).find('td:eq(1)').html(),
driver: $(this).find('td:eq(2)').html(),
place: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
missionCode: $("#missionCode").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
deta: detaArr
});
$.when(saveDeta(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
}
This is the controller
namespace WebApplication2.Controllers
{
public class DetasController : Controller
{
ETHADAMISEntities db = new ETHADAMISEntities();
public ActionResult Index()
{
List<Test> DetaAndTest = db.Tests.ToList();
return View(DetaAndTest);
}
public ActionResult SaveDeta(string missionCode, DateTime startDate, DateTime endDate, Deta[] deta)
{
string result = "Error! Test Detail Is Not Complete!";
if (missionCode != null && startDate != null && endDate != null && deta != null)
{
var tstId = Guid.NewGuid();
Test model = new Test
{
TestID = tstId,
MissionCode = missionCode,
StartDate = startDate,
EndDate = endDate
};
db.Tests.Add(model);
foreach (var item in deta)
{
var id = Guid.NewGuid();
Deta O = new Deta
{
DetaId = id,
TestType = item.TestType,
TestDate = item.TestDate,
Driver = item.Driver,
Place = item.Place,
TestID = tstId
};
db.Detas.Add(O);
}
db.SaveChanges();
result = "Success! Test with Detail Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
This is the view
#model IEnumerable<WebApplication2.Models.Test>
<br /><br />
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<h2 class="panel-title pull-left" style="margin-left:10px;">
<strong>Test Details</strong>
</h2>
<button style="margin-right:10px" class="btn btn-primary pull-right" onclick="addNewDeta()">New Test</button>
</div>
</div>
#*Receive All Database Data From Controller And Display Those Data In Client Side*#
#if (Model.Count() != 0)
{
foreach (var item in Model)
{
<div class="panel-body">
<table class="table table-striped table-responsive">
<tbody>
<tr>
<td>Mission Code : #item.MissionCode </td>
<td>Start Date : #item.StartDate </td>
<td>End Date : #item.EndDate</td>
</tr>
<tr>
<td colspan="3">
<table class="table table-bordered">
<tbody>
<tr>
<th>Test Type</th>
<th>Test Date</th>
<th>Driver</th>
<th>Place</th>
</tr>
#foreach (var deta in item.Detas)
{
<tr>
<td>#deta.TestType</td>
<td>#deta.TestDate</td>
<td>#deta.Driver</td>
<td>#deta.Place</td>
</tr>
}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
}
}
else
{
<div class="panel-body">
<h3 style="color:red;">Empty!</h3>
</div>
}
</div>
#*Desing Bootstrap Modal With Order Form*#
<div class="modal fade" id="newDetaModal">
<div class="modal-dialog modal-lg" style=" width: 900px !important;">
<div class="modal-content">
<div class="modal-header">
×
<h4>Add New Test</h4>
</div>
<form id="NewDetailForm">
<div class="modal-body">
#*Test Details*#
<h5 style="color:#ff6347">Tests</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="TestID" />
<div class="form-group">
<label class="control-label col-md-2">
Mission Code
</label>
<div class="col-md-4">
<input type="text" id="missionCode" name="missionCode" placeholder="Mission Code" class="form-control" />
</div>
<label class="control-label col-md-2">
Start Date
</label>
<div class="col-md-4">
<input type="text" id="startDate" name="startDate" placeholder="Start Date" class="form-control" />
</div>
<label class="control-label col-md-2">
End Date
</label>
<div class="col-md-4">
<input type="text" id="endDate" name="endDate" placeholder="End Date" class="form-control" />
</div>
</div>
</div>
#*Test Detail Details*#
<h5 style="margin-top:10px;color:#ff6347">Test Details</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="DetaId" />
<div class="form-group">
<label class="control-label col-md-2">
Test Type
</label>
<div class="col-md-4">
<input type="text" id="testType" name="testType" placeholder="Test Type" class="form-control" />
</div>
<label class="control-label col-md-2">
Test Date
</label>
<div class="col-md-4">
<input type="datetime" id="testDate" name="testDate" placeholder="Test Date" class="form-control" />
</div>
<label class="control-label col-md-2">
Place
</label>
<div class="col-md-4">
<input type="text" id="place" name="place" placeholder="Place" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">
Driver
</label>
<div class="col-md-4">
<input type="text" id="driver" name="driver" placeholder="Driver" class="form-control" />
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">AddToList</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead>
<tr>
<th style="width:30%">Test Type</th>
<th style="width:20%">Test Date</th>
<th style="width:25%">Driver</th>
<th style="width:15%">Place</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveDeta" type="submit" class="btn btn-success">Save Test Detail</button>
</div>
</form>
</div>
</div>
</div>

HttpPostedFileBase is coming null

below is the code in my View
#using ClaimBuildMVC.Models
#model IEnumerable<Asset>
#{
ViewBag.Title = "AssetsPage";
Layout = "~/Views/Shared/_SuperAdminLayout.cshtml";
}
<script type="text/javascript">
</script>
#using (Html.BeginForm("AssetsPage", "SuperAdmin", FormMethod.Post,new{enctype = "multipart/form-data"}))
{
<div class="Content-inner-pages">
<div class="TopHeading TopHeading2">
<h2>Assets</h2>
<a class="CreateBtn AssetsBtn" href="Javascript:void(0);" onclick="javascript:$('#hdnIsNew').val('1')">Add Asset</a>
<div class="clearfix"></div>
</div>
<input type="hidden" id="hdnIsNew" value="1" />
<input type="hidden" id="hdnRecId" />
<!-- Slide Popup panel -->
<div class="cd-panel from-right AddAssetForm">
<header class="cd-panel-header">
<h3>Add Asset</h3>
Close
</header>
<div class="cd-panel-container">
<div class="cd-panel-content">
<div class="form-horizontal form-details popup-box">
<div class="form-group">
<label class="col-md-5 control-label">
Asset Title
</label>
<div class="col-md-7">
<input type="text" id="txtTitle" name="txtTitle" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Description</label>
<div class="col-md-7">
<textarea id="txtDesc" class="form-control" cols="5" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Attachment</label>
<div class="col-md-7">
<input type="file" id="file" class="custom-file-input">
</div>
</div>
<div class="form-group">
<div class="col-md-7 col-md-offset-5">
<input type="submit" value="Save" name="actionType" class="btn-class btn-success">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="box">
<div class="box-content Custom-DataTable">
<table id="AdministationAssets" class="table table-hover dt-responsive CustomDatable AdministationAssetsTable" cellspacing="0" width="100%">
<thead>
<tr>
<th style="width:5%;">Assets</th>
<th style="width:15%;">
#Html.DisplayNameFor(model =>model.Title)
</th>
<th style="width:50%;">
#Html.DisplayNameFor(model =>model.Description)
</th>
<th style="width:8%;">Options</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td></td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem =>item.Description)
</td>
<td>
#Html.ActionLink("Edit", "AddEditRecord", new{ id = item.ID }, new { #class = "ActionEdit AssetEdit", onclick ="javascript:GetEditDetails(" + item.ID + ");" })
#Html.ActionLink("Delete", "AssetDelete", new{ id = item.ID }, new { #class = "ActionDelete", onclick = "return confirm('Are You Sure delete this record?');", })
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
and below is my controller that what i want to call when click on save button but 'img' is coming as null and after searching in google i found that to add #using(Html.BeginForm()) but still it is coming as null
[HttpPost]
public ActionResult AssetsPage(Asset ast, HttpPostedFileBase file)
{
using (GenericUnitOfWork gc = new GenericUnitOfWork())
{
if (HttpContext.Request.Files.Count > 0)
{
ast.ContainerName = "reports";
ast.BlobName = HttpContext.Request.Files[0].FileName;
ast.BlobUrl = BlobUtilities.CreateBlob(ast.ContainerName, ast.BlobName, null, GetStream(HttpContext.Request.Files[0].FileName));
ast.FileName = HttpContext.Request.Files[0].FileName;
}
gc.GetRepoInstance<Asset>().Add(ast);
gc.SaveChanges();
}
return RedirectToAction("AssetsPage");
}
Not able to find the solution. Please help or give some reference if possible.
Asp.Net MVC default model binding works with name attribute, So add name="file" attribute with input type="file" as shown :-
<input type="file" name="file" id="file" class="custom-file-input">

mvc Get a value of element in different cshtml with jquery

I have a page ("mypage.cshtml") and two partial view page ( partial1.cshtml, partial2.cshtml )
when Im in mypage click a button and display a modal which call partial1 with #Html.Partial("patial1") in a modal(bootstrap modal). it consist of html. when I a click a button on this modal it calls another modal consist of partial2..
Here is the issue; When I load the page begining (in mypage ) I need to get the value of checkbox that standing in second modal, that is partial2.
During I view this modal I can get this value with this:
$("input[type='checkbox'][id='4']").val();
it gives me the value which I expect but at the begining(in mypage.cshtml) this returns "undefined" :S
I couldnt understand this stuation both of these modal located in mypage but why I cant get these elements values untill I reach them ?
here is view mypage:
<div id="stack1" class="modal fade" tabindex="-1" data-width="400">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">#Model.Kurulus.TESIS_ADI</h4>
</div>
<div class="modal-body">
<form id="formKaydet" method="post" action="../KurulusBilgileri/KurulusBilgileriniGuncelle">
<div class="row">
<div class="col-md-12">
#Html.Partial("KurulusBilgileriniGuncelle", Model)
</div>
<div class="modal-footer">
<input type="hidden" name="SANAYI_TIPI" id="input_id" />
<input type="hidden" name="SANAYI_TIPI_DIGER" id="input_sanayitipi" />
<button type="button" data-dismiss="modal" class="btn default">Geri</button>
<a class="btn orange" onclick="sanayitipleriKaydet()">Kaydet A</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="stack2" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">#Model.Kurulus.TESIS_ADI</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
#Html.Partial("SanayiTipiSecim", Model.SanayitipiModel)
</div>
</div>
</div>
<div class="modal-footer">
#*<button type="button" data-dismiss="modal" class="btn">Close</button>
<button type="button" class="btn yellow">Ok</button>*#
</div>
</div>
</div>
</div>
and my second modal (SanayiTipiSecim)
<table class="table-full-width">
<thead>
<tr>
<th></th>
<th><strong>Sanayici Tipi</strong></th>
<th><strong>Açıklama</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" onclick="javascript:sanayitipiTotextarea(1)" id="1" value="Boya Sanayi">
</td>
<td>
Boya Sanayi
</td>
<td>
Boya üretimi yapan imalathaneler
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" onclick="javascript:sanayitipiTotextarea(2)" id="2" value="Enerji üretimi ve dağıtımı">
</td>
<td>
Enerji üretimi ve dağıtımı
</td>
<td>
Ör. Enerji üretim merkezleri, enerji ara istasyonları vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="3" onclick="javascript:sanayitipiTotextarea(3)" value="Elektrik ve Elektronik Mühendisliği">
</td>
<td>
Elektrik ve Elektronik Mühendisliği
</td>
<td>
Elektronik parçaların üretimi vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="4" onclick="javascript:sanayitipiTotextarea(4)" value="Genel Mühendislik, imalat ve montaj">
</td>
<td>
Genel Mühendislik, imalat ve montaj
</td>
<td>
Herhangi bir mühendislik aktivitesi, üretim veya montaj vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="5" onclick="javascript:sanayitipiTotextarea(5)" value="Gıda ve içecek">
</td>
<td>
Gıda ve içecek
</td>
<td>
Gıda, alkollü içki vb?
</td>
script blocks in first page:
<script src="~/Scripts/js/kurulusbilgileri.js"></script>
<script>
sanayitipleriKaydet = function () {
debugger
var data = new Object()
data.ISIM = $("input[name='ISIM']").val();
data.ADRES_METIN = $("input[name='ADRES_METIN']").val();
data.TELEFON = $("input[name='TELEFON']").val();
data.FAKS = $("input[name='FAKS']").val();
data.E_POSTA = $("input[name='E_POSTA']").val();
data.SORUMLU_ISIM = $("input[name='SORUMLU_ISIM']").val();
data.SORUMLU_SOYISIM = $("input[name='SORUMLU_SOYISIM']").val();
data.FAALIYET_ALANI = $("input[name='FAALIYET_ALANI']").val();
data.CEVRE_BILGI = $("input[name='CEVRE_BILGI']").val();
data.BELEDIYE_MUCAVIR_ALAN = $("input[name='BELEDIYE_MUCAVIR_ALAN']:checked").val();
debugger
data.OSB_YERLESIK = $("input[name='OSB_YERLESIK']:checked").val();
data.KIYI_TESISI = $("input[name='KIYI_TESISI']:checked").val();
data.VERSIYON = $("input[name='VERSIYON']:checked").val();
data.SANAYI_TIPI = window.localStorage.getItem("sanayitipiid");
window.localStorage.removeItem("sanayitipiid");
debugger
var jsondata = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: 'application/json',
url: "/KurulusBilgileri/KurulusBilgileriniGuncelle",
data: jsondata,
success: function (result) {
debugger
var jsondata = JSON.parse(result)
if (jsondata.Passed) {
debugger
$('#tdISIM').empty();
$('#tdISIM').append(data.ISIM);
$('#tdADRES_METIN').empty();
$('#tdADRES_METIN').append(jsondata.data.ADRES_METIN);
$('#tdTELEFON').empty();
$('#tdTELEFON').append(jsondata.data.TELEFON);
$('#tdFAKS').empty();
$('#tdFAKS').append(jsondata.data.FAKS);
$('#tdE_POSTA').empty();
$('#tdE_POSTA').append(jsondata.data.E_POSTA);
$('#tdSORUMLU_ISIM').empty();
$('#tdSORUMLU_ISIM').append(jsondata.data.SORUMLU_ISIM);
$('#tdSANAYI_TIPI > #tdtxtSANAYI_TIPI').empty();
$('#tdSANAYI_TIPI > #tdtxtSANAYI_TIPI').append(jsondata.data.SANAYI_TIPI);//sanayitipi id si...
$('#tdFAALIYET_ALANI > #tdtxtFAALIYET_ALANI').empty();
$('#tdFAALIYET_ALANI > #tdtxtFAALIYET_ALANI').append(jsondata.data.FAALIYET_ALANI);
$('#tdCEVRE_BILGI > #tdtxtCEVRE_BILGI').empty();
$('#tdCEVRE_BILGI > #tdtxtCEVRE_BILGI').append(jsondata.data.CEVRE_BILGI);
debugger
if (jsondata.data.BELEDIYE_MUCAVIR_ALAN == "1") {
$("#tdBELEDIYE_MUCAVIR_ALAN > input[name='radioBelediyeMucavirAlan']").prop('checked', true);
}
else
$("#tdBELEDIYE_MUCAVIR_ALAN > input[name='radioBelediyeMucavirAlan']").prop('checked',false);
if (jsondata.data.OSB_YERLESIK == "1") {
$("#tdOSB_YERLESIK > input[name='radioOsbYerlesik']").prop('checked', true);
}
else
$("#tdOSB_YERLESIK > input[name='radioOsbYerlesik']").prop('checked',false);
if (jsondata.data.KIYI_TESISI == "1") {
$("#tdKIYI_TESISI > input[name='radioKiyiTesisi']").prop('checked', true);
}
else
$("#tdKIYI_TESISI > input[name='radioKiyiTesisi']").prop('checked',false);
if (jsondata.data.VERSIYON == "1") {
$("#tdVERSIYON > input[name='radioVersion']").prop('checked', true);
}
else
$("#tdVERSIYON > input[name='radioVersion']").prop('checked',false);
}
},
error: function () {
alert("ajax process in error");
}
});
}
</script>
kurulusbilgileri.js:
$(function () {
$("#btnSanayiTipiKaydet").on('click', sanayitipleriKaydet)
});
sanayiTipiTextGetir = function (id)
{
var text = $('input[id=' + id + ']').val();
debugger;
return text;
}
sanayitipilistesinigoster = function () {
$("#stack2").show();
}
sanayitipiTotextarea = function (id) {
$("#divSanayiTipi").show(600, null);
var sanayitipi = $("#" + id).val();
window.localStorage.setItem("sanayitipiid", id);
$("#input_sanayitipi").val(sanayitipi);
$("#input_id").val(id);
$("#stack2").modal('toggle');
}
Since you load your partial trough a modal, I'm assuming that the actual loading is done using AJAX. This means that when you first load your HTML page (the initial one), the partial is not yet part of the DOM (might have not been requested from the server). This in turn means that you checkbox is also not part of the DOM, and therefore is returned as undefined.

jQuery UI Tabs refreshes after button click

I have jQuery UI Tabs page:
<div class="addTheatreContainer">
<div class="addTheatreHeader">
<span class="txtLightboxTitle">ADD THEATRE</span>
</div><!--end/ .addTheatreHeader-->
<!-- Tabs -->
<div id="tabs">
<ul>
<li>
1 B.C.
</li>
<li>
2 Alberta
</li>
</ul>
<div id="#tabs-1">
<table class="table5">
<tr>
<td width="20">
<fieldset class="checkboxes">
<label class="label_check">
<input name="ctl10" type="checkbox" />
</label>
</fieldset>
</td>
<td width="40">ID</td>
<td width="120">Location</td>
<td width="120">Region</td>
<td width="120">City</td>
<td width="70">Province</td>
</tr>
</table>
</div>
<div id="#tabs-2">
<table class="table5">
<tr>
<td width="20"><fieldset class="checkboxes"><label class="label_check"><input name="ctl22" type="checkbox" /></label></fieldset></td>
<td width="40">ID</td>
<td width="120">Location</td>
<td width="120">Region</td>
<td width="120">City</td>
<td width="70">Province</td>
</tr>
</table>
</div>
</div><!--end/ #tabs-->
<div class="ButtonAlignRight">
<button id="btnAddAndCloseTheatre" runat="server" class="btnAddandCloseTheatre" >Add & Close</button>
<button id="btnAddTheatre" runat="server" class="btnAddTheatre" onclick="AddLocations()">Add</button>
<button id="btnClose" runat="server" class="btnClose">Close</button>
</div>
</div>
When I click the Add button. The whole page refreshes and I dont want it to since I am storing values in a global variable.
JS:
function AddLocations()
{
var allChecboxes = $("#tabs").tabs("options", "active").find(".checkboxes");
var allCheckedLocations = allChecboxes.find(".cbLocation").each(function () {
var checkbox = $(this);
if (checkbox.prop("checked") == true)
{
var checkboxId = checkbox.attr("id");
var locationId = parseInt(checkboxId.replace("cbLocation_", ""));
if (typeof (locationId) == "number" && isNaN(locationId) == false) {
AddedLocationsList.push(locationId);
}
//checkbox.parents(".row").fadeOut();
}
});
}
AddedLocationsList is a global variable.This function works perfectly but since the page is refreshed the variable is set back to []. I don't know why the page is being refreshed. Is there a jQuery UI callback?

IEnumerable is null when I expect values

I am using the approach in this article to return a list of objects that are posted to my action. My method looks like:
//
// POST: /LeaveRequest/Create
[Authorize, HttpPost]
public ActionResult Create(LeaveRequest leaveRequest, IEnumerable<DayRequested> requestedDays)
{
return RedirectToAction("Index", lrRepository.GetLeaveRequests(472940821));
}
leaveRequest has the data that I expect. requestedDays contains the number of rows I expect, but all of the rows contain null in each field. Any ideas of what I may be missing?
Here is the View code:
Create.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<EmployeePayroll.ViewModels.LeaveRequestViewModel>" %>
<%# Import Namespace="EmployeePayroll.Helpers"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Create New Leave Request</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create New Leave Request</h2>
<div><%= Html.ActionLink("Back to List", "Index") %></div>
<%= Html.Partial("RequestEditor", Model) %>
<div><%= Html.ActionLink("Back to List", "Index") %></div>
</asp:Content>
RequestEditor.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EmployeePayroll.ViewModels.LeaveRequestViewModel>" %>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Request Details</legend>
<table>
<tbody id="editorRows">
<tr><th>Date</th><th>Time</th><th>Hours</th><th>Request Type</th><th></th></tr>
<% foreach (var item in Model.DaysRequested)
Html.RenderPartial("RequestedDayRow", new EmployeePayroll.ViewModels.LeaveRequestRow(item, Model.LeaveRequestType)); %>
</tbody>
</table>
<p><%= Html.ActionLink("Add Day", "BlankRequestedDayRow", null, new { id = "addItem" })%></p>
<p>Type your time to sign your request.</p>
<p><%= Html.LabelFor(model => model.LeaveRequest.EmployeeSignature) %>: <%= Html.TextBoxFor(model => model.LeaveRequest.EmployeeSignature, new { Class="required" })%></p>
<p><%= Html.LabelFor(model => model.LeaveRequest.EmployeeComment) %>: <%= Html.TextBoxFor(model => model.LeaveRequest.EmployeeComment) %></p>
<p><input type="submit" value="Submit Request" /></p>
</fieldset>
<% } %>
RequestedDayRow.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EmployeePayroll.ViewModels.LeaveRequestRow>" %>
<%# Import Namespace="EmployeePayroll.Helpers"%>
<tr class="editorRow">
<% using (Html.BeginCollectionItem("requestedDays"))
{ %>
<td><%= Html.TextBoxFor(model => model.DayRequested.DateOfLeave, new { Class = "datepicker", Maxlength = "10" })%></td>
<td><%= Html.TextBoxFor(model => model.DayRequested.TimeOfLeave, new { Class = "timedropdown", Maxlength = "8" })%></td>
<td><%= Html.TextBoxFor(model => model.DayRequested.HoursRequested, new { Class = "hoursdropdown", Maxlength = "4" })%></td>
<td><%= Html.DropDownListFor(model => model.DayRequested.RequestType,
new SelectList(Model.LeaveRequestType, "Value", "Text", Model.DayRequested.RequestType), "(Select)")%></td>
<td><img src="../../images/site_icons/16/69.png" title="Delete" alt="Delete" border="0" /></td>
<% } %>
</tr>
Here is the generated form:
<form method="post" action="/LeaveRequest/Create">
<fieldset>
<legend>Request Details</legend>
<table>
<tbody id="editorRows">
<tr><th>Date</th><th>Time</th><th>Hours</th><th>Request Type</th><th></th></tr>
<tr class="editorRow">
<input type="hidden" value="c43391a3-7fe4-4514-8b27-d00995d64848" autocomplete="off" name="requestedDays.index">
<td><input type="text" value="11/17/2010" name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].DayRequested.DateOfLeave" id="requestedDays_c43391a3-7fe4-4514-8b27-d00995d64848__DayRequested_DateOfLeave" maxlength="10" class="datepicker"></td>
<td><input type="text" value="8:00 AM" name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].DayRequested.TimeOfLeave" id="requestedDays_c43391a3-7fe4-4514-8b27-d00995d64848__DayRequested_TimeOfLeave" maxlength="8" class="timedropdown"></td>
<td><input type="text" value="8" name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].DayRequested.HoursRequested" id="requestedDays_c43391a3-7fe4-4514-8b27-d00995d64848__DayRequested_HoursRequested" maxlength="4" class="hoursdropdown"></td>
<td><select name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].DayRequested.RequestType" id="requestedDays_c43391a3-7fe4-4514-8b27-d00995d64848__DayRequested_RequestType"><option value="">(Select)</option>
</select></td>
<td><a class="deleteRow" href="#"><img border="0" alt="Delete" title="Delete" src="../../images/site_icons/16/69.png"></a></td>
</tr>
<tr class="editorRow">
<input type="hidden" value="a24b74f6-2947-4ec5-a817-f938d6fe4e24" autocomplete="off" name="requestedDays.index">
<td><input type="text" value="11/17/2010" name="requestedDays[a24b74f6-2947-4ec5-a817-f938d6fe4e24].DayRequested.DateOfLeave" id="requestedDays_a24b74f6-2947-4ec5-a817-f938d6fe4e24__DayRequested_DateOfLeave" maxlength="10" class="datepicker"></td>
<td><input type="text" value="8:00 AM" name="requestedDays[a24b74f6-2947-4ec5-a817-f938d6fe4e24].DayRequested.TimeOfLeave" id="requestedDays_a24b74f6-2947-4ec5-a817-f938d6fe4e24__DayRequested_TimeOfLeave" maxlength="8" class="timedropdown"></td>
<td><input type="text" value="8" name="requestedDays[a24b74f6-2947-4ec5-a817-f938d6fe4e24].DayRequested.HoursRequested" id="requestedDays_a24b74f6-2947-4ec5-a817-f938d6fe4e24__DayRequested_HoursRequested" maxlength="4" class="hoursdropdown"></td>
<td><select name="requestedDays[a24b74f6-2947-4ec5-a817-f938d6fe4e24].DayRequested.RequestType" id="requestedDays_a24b74f6-2947-4ec5-a817-f938d6fe4e24__DayRequested_RequestType"><option value="">(Select)</option>
</select></td>
<td><a class="deleteRow" href="#"><img border="0" alt="Delete" title="Delete" src="../../images/site_icons/16/69.png"></a></td>
</tr>
</tbody>
</table>
<p><a id="addItem" href="/LeaveRequest/BlankRequestedDayRow">Add Day</a></p>
<p>Type your time to sign your request.</p>
<p><label for="LeaveRequest_EmployeeSignature">Employee Signature</label>: <input type="text" value="" name="LeaveRequest.EmployeeSignature" id="LeaveRequest_EmployeeSignature" class="required"></p>
<p><label for="LeaveRequest_EmployeeComment">Employee Comment</label>: <input type="text" value="" name="LeaveRequest.EmployeeComment" id="LeaveRequest_EmployeeComment"></p>
<p><input type="submit" value="Submit Request"></p>
</fieldset>
</form>
The form posts the following information:
Parametersapplication/x-www-form-urlencoded
LeaveRequest.EmployeeComm... Comment
LeaveRequest.EmployeeSign... Michael Wills
requestedDays.index 549a7c9a-9c7d-4032-a1cd-6bfda92bf1f2
requestedDays.index 2838b025-d971-4d98-a081-5ea0c559aebb
requestedDays[2838b025-d9... 11/17/2010
requestedDays[2838b025-d9... 8
requestedDays[2838b025-d9... 1
requestedDays[2838b025-d9... 8:00 AM
requestedDays[549a7c9a-9c... 11/17/2010
requestedDays[549a7c9a-9c... 8
requestedDays[549a7c9a-9c... 1
requestedDays[549a7c9a-9c... 8:00 AM
Source
Content-Type: application/x-www-form-urlencoded
Content-Length: 907
requestedDays.index=549a7c9a-9c7d-4032-a1cd-6bfda92bf1f2&requestedDays%5B549a7c9a-9c7d-4032-a1cd-6bfda92bf1f2%5D.DayRequested.DateOfLeave=11%2F17%2F2010&requestedDays%5B549a7c9a-9c7d-4032-a1cd-6bfda92bf1f2%5D.DayRequested.TimeOfLeave=8%3A00+AM&requestedDays%5B549a7c9a-9c7d-4032-a1cd-6bfda92bf1f2%5D.DayRequested.HoursRequested=8&requestedDays%5B549a7c9a-9c7d-4032-a1cd-6bfda92bf1f2%5D.DayRequested.RequestType=1&requestedDays.index=2838b025-d971-4d98-a081-5ea0c559aebb&requestedDays%5B2838b025-d971-4d98-a081-5ea0c559aebb%5D.DayRequested.DateOfLeave=11%2F17%2F2010&requestedDays%5B2838b025-d971-4d98-a081-5ea0c559aebb%5D.DayRequested.TimeOfLeave=8%3A00+AM&requestedDays%5B2838b025-d971-4d98-a081-5ea0c559aebb%5D.DayRequested.HoursRequested=8&requestedDays%5B2838b025-d971-4d98-a081-5ea0c559aebb%5D.DayRequested.RequestType=1&LeaveRequest.EmployeeSignature=Michael+Wills&LeaveRequest.EmployeeComment=Comment
Looks like you may need to remove DayRequested from your hidden form field name.
For example:
... I removed some of the attributes because the only thing that's changed here is the name attribute.
<input type="hidden" name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].DateOfLeave" value="11/17/2010" />
<input type="hidden" name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].TimeOfLeave" value="8:00 AM" />
<input type="hidden" name="requestedDays[c43391a3-7fe4-4514-8b27-d00995d64848].HoursRequested" value="8" />
...
As discussed in the question comments, it seems odd that ASP.NET MVC would generate the source you gave, as that suggests that each RequestedDay object has a single property called RequestedDay.
The object you're binding to is called requestedDays, and the guid is an indication of which position in the collection you're binding to (stating the obvious here, I know!). Therefore, stating the object name (DayRequested) doesn't make any sense, since the model binder should already know this, and just needs to know which property of that class it's dealing with.
see this post from Haacked - Model Binding To A List
it might help you

Resources