HttpPostedFileBase is coming null - asp.net-mvc

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

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>

Why is my anchor tag in Thymeleaf is not redirecting to the local file

I am trying to redirect to another local web page using a tag in Thymeleaf and Spring boot but it is
not working. I am redirecting from index.html to addEdit.html which are in the same folder.
Here is my code.
index.html
<div class="container">
<p th:text="${message}"></p>
<a th:href="#{/addEdit.html}" class="btn btn-outline-info">Add Employee</a> //not working
<table class="table table-bordered table-dark">
<thead class="">
<tr>
<th>#</th>
<th>Name</th>
<th>Departmen</th>
<th>Position</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="employee : ${employees}" >
<th th:text="${employee.id}"></th>
<td th:text="${employee.name}"></td>
<td th:text="${employee.department}"></td>
<td th:text="${employee.position}"></td>
<td>
<form action="delete">
<input type="submit" value="Delete" class="btn btn-outline-warning"/>
</form>
</td>
<td>
<form action="edit">
<input type="submit" value="Edit" class="btn btn-outline-info"/>
</form>
</td>
</tr>
</tbody>
</table>
</div>
my EmployeeController
#Autowired
private employeeRepo repo;
#RequestMapping("/")
public String home(Model model) {
List<Employee> list = new ArrayList<>();
list = repo.findAll();
model.addAttribute("employees",list);
return "index";
}
#PostMapping("/addEmployee")
public void addEmployee(Employee employee,Model model) {
repo.save(employee);
model.addAttribute("message","Add Successfully");
home(model);
}
my addEdit.html
<div class="container bg-light">
<form action="addEmployee">
<input class="form-control form-control-sm" type="text" placeholder="Name" name="name"><br>
<input class="form-control form-control-sm" type="text" placeholder="Department" name="department"><br>
<input class="form-control form-control-sm" type="text" placeholder="Position" name="postion"><br/>
<input type="submit" value="Add Employee" class="btn btn-outline-success btn-lg btn-block">
</form>
</div>
You should not include the .html in your link. The link should point to a URL that your controller exposes. There is currently no controller method that exposes the /addEdit url for example.
So update your controller:
#GetMapping
public String addEmployee(Model model) {
// add model attributes here as needed first
return "addEdit" // This refers to the view, so 'addEdit.html'
}
Now update the link to:
<a th:href="#{/addEdit}" class="btn btn-outline-info">Add Employee</a>

View/open file url

I have a view that creates a document with a Title, Date, and name of file that I upload. Once that document is created it is returned to a View that shows the document that I just created and is stored in a database.
Here is the code that creates the document:
<form asp-action="CreateDirectorDocument" role="form" class="form-
horizontal">
<div asp-validation-summary="ModelOnly" class="alert-
danger text-danger"></div>
<div class="form-group">
<div class="col-md-10"><a asp-
action="Index">View Documents</a></div>
</div>
<div class="form-group">
<div class="col-md-10"><label asp-for="Date">
</label></div>
<div class="col-sm-2"><input asp-for="Date" />
</div>
</div>
<div class="form-group">
<div class="col-md-2"><label asp-
for="DocFile"></label></div>
<div class="col-md-4">
<input asp-for="DocFile" type="file"
multiple>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"><label asp-for="Title">
</label></div>
<div class="col-sm-2"><input asp-for="Title"
/></div>
</div>
</form>
View that is return after document has been created:
<table>
<thead>
<tr>
<th class="col-md-2" style="border-bottom: solid">
</th>
<th class="col-md-2" style="border-bottom:
solid">Title</th>
<th class="col-md-2" style="border-bottom:
solid">Date</th>
<th class="col-md-2" style="border-bottom: solid">
</th>
</tr>
</thead>
<tbody>
#foreach (var dirDocs in Model.Docs)
{
<tr>
<td class="col-md-2">
<a asp-area="Admin" asp-controller="Docs"
asp-action="EditDirectorDocument" asp-route-
id="#dirDocs.Id">Edit</a>
<a asp-area="Admin" asp-controller="Docs"
asp-action="DeleteDirectorDocument" asp-route-
returnViewName="#returnViewName" asp-route-id="#dirDocs.Id"
onclick="return confirm('Are you sure you want to delete
this document?');">Delete</a>
</td>
<td class="col-md-2">#dirDocs.Title</td>
<td class="col-md-2">#dirDocs.Date</td>
<td class="col-md-2"><a asp-route-
id="#dirDocs.Url" target="_blank">Open</a></td>
</tr>
}
</tbody>
</table>
The file that is uploaded gets stored as a document file and is created as a url for the user to view. How do I do this in MVC. Is that set up in the controller? If so how is that done?
Not sure, but I think you just need:
Open
Instead of
<a asp-route-id="#dirDocs.Url" target="_blank">Open</a>
I assume you mean you get a URL back from the upload process that you want to display to the user so they can click on it and see the file they uploaded.
If you wanted to display some thing like that inline you could probably use an iframe whose src is set to #dirDocs.Url:
<iframe src="#dirDocs.Url"></iframe>

How Do I solve "Sequence contains no elements" error

I have an index view that gets a parameter from an Action link. Sometimes there won't be a record and in that case I want the #Model.Count to simply show 0. That was working just fine. I then need a button to pass that same parameter to a Create view to add a new (initial) record and display on the previous index page. This is where I hit a problem.
<input class="btn btn-sm btn-info" type="button" value="Add To Roster" onclick=" location.href = '#Url.Action("Create", "Enrollments", new {enrollments_CurrentSites = Model.First().Enrollments_CurrentSite}, null)' "/>
If there is no record, instead of showing a count of 0, I now get an error "Sequence Contains No Elements". I thought that maybe there is a null Model and tried to check for it, but no go. If there is one or more records, then the Count is displayed and the "Add To Roster" button performs as expected.
Can someone help me solve this error?
Error Code:
#model IEnumerable<SlamJammersData.Model.Enrollments>
#{
ViewBag.Title = "Rosters";
}
<div class="container-fluid">
<div class="panel panel-info">
<div class="panel-body">
<div class="container">
<div class="row">
#if (Model == null)
{
<h4>Roster count: 0</h4>
}
else
{
<p>
<h4>Roster count: #Model.Count() </h4>
</p>
}
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-sm-2">
<p>
<input class="btn btn-sm btn-info" type="button" value="Add To Roster" onclick=" location.href = '#Url.Action("Create", "Enrollments", new {enrollments_CurrentSites = Model.First().Enrollments_CurrentSite}, null)' "/>
</p>
</div>
<div class="col-sm-2">
<div class="col-sm-2">
<input type="button" class="btn btn-default btn-sm" value="Attendance" />
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
<table class="table table-striped table-condensed table-responsive">
<tr>
<th>Player</th>
<th>#Html.DisplayNameFor(model => model.StartTime)</th>
<th></th>
<th></th>
</tr>
#foreach(var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.FullName)</td>
<td>#Html.DisplayFor(modelItem => item.StartTime)</td>
<td>
#Html.ActionLink("Details", "Details", new{id = item.Id})
</td>
<td>
#Html.ActionLink("Edit", "Edit", new {id = item.Id})
</td>
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
Sending code:
#Html.ActionLink("Rosters", "Index", "Enrollments", new { id = item.Id }, null) |

MVC; How do you avoid ID name collisions when using tabs?

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

Resources