Saving a moved item - jquery-ui

When I use a move item from a selection list to another list using jQuery it moves well but when I reload the page it goes back to the previous list. I want to know how can I save it so when I reload the page it doesn't go back?
<script>
$(document).ready(function () {
$('#btnRight').click(function (e) {
var selectedOpts = $('#lstBox1 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnLeft').click(function (e) {
var selectedOpts = $('#lstBox2 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox1').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnRight2').click(function (e) {
var selectedOpts = $('#lstBox2 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox3').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnLeft2').click(function (e) {
var selectedOpts = $('#lstBox3 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
});
</script>
#foreach (var item in Model)
{
<hr />
<table>
<tr>
<td style='width:160px;'>
<b>TO DO:</b><br />
<select multiple="multiple" id='lstBox1'>
<option>#Html.DisplayFor(model => item.Events.Vanue)</option>
</select>
</td>
<td style='width:50px;text-align:center;vertical-align:middle;'>
<input type="button" id="btnRight" value="-" />
<br /><input type="button" id="btnLeft" value="<" />
</td>
<td style='width:200px;'>
<b>IN PROGRESS: </b><br />
<select multiple="multiple" id='lstBox2'>
</select>
</td>
<td style='width:50px;text-align:center;vertical-align:middle;'>
<input type="button" id="btnRight2" value="-" />
<br /><input type="button" id="btnLeft2" value="<" />
</td>
<td style='width:160px;'>
<b>DONE: </b><br />
<select multiple="multiple" id='lstBox3'>
</select>
</td>
</tr>
</table>

You need to find a way to save the website's state. There are a lot of options. You can start with this article on localStorage. I found it be a good primer.

Related

MVC Validation checkbox

I am trying to make sure that at least one 'input checkbox is checked in this list there is about 10 items but I am not sure how to do this? Do I need a flag in the model?
<div>* Data</div>
#Html.ValidationMessageFor(x => x.flgData,"", new { #class = "text-danger" })
<ul>
#foreach (var item in Model.ListOfData)
{
<li>
<input type="checkbox" value="#item.Value" name="chk" />
<label asp-for="#item.Selected">#Html.Raw(#item.Name)</label>
<input type="hidden" asp-for="#item.DictionaryId" />
<input type="hidden" asp-for="#item.Name" />
</li>
}
</ul>
You could loop though all the checkbox and check if it is checked
HTML
<input type="button" id="btnSubmitCB" value="Submit" class="btn btn-primary" />
<input type="checkbox" class="chkbox" value="Bike" /> Bike
<input type="checkbox" class="chkbox" value="Car" /> Car
<input type="checkbox" class="chkbox" value="Boat" /> Boat
JQuery
$(document).ready(function () {
$('#btnSubmitCB').click(function () {
var cbChecked = false;
$('input[type=checkbox]').each(function () {
if (this.checked) {
cbChecked = true;
return false;
}
});
if (cbChecked) {
alert("At least one checkbox is checked");
}
else {
alert("No checkbox is checked");
}
});
});
Another way without using .each function
$(document).ready(function () {
$('#btnSubmitCB').bind("click", function () {
let checkedCount = $('input[type=checkbox]:checked').length;
if (checkedCount == 0) {
alert("no checkbox has been checked")
}
else {
alert("checkbox has been checked");
}
});
});

Cant display values to Textbox's at second time using Jquery

I am developing MVC application.
I have shown the confirm modal box.
It works properly only at once.... If I open it again it didnt work at all...
check below picture....
when I put the entries in the dispatch text box(34), on blur event it multiplies bundle size value(60) and shows in Pisces text box (2040). its working fine,
when I close the box and open it again and put the values again in dispatch text box, its not working at all...
Here is my code...
<h2 style="font-size:22px;">Dispatch </h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Create", "Dispatch", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmCreate" }))
{
#Html.ValidationSummary(true)
<div class="row-fluid">
<div class="span12 roundedDiv" >
<div class="span12" style="margin-left:0px; margin-bottom:10px;">
<legend style="color:#ee8929; font-size:16px;">Primary Information</legend>
</div>
<div class="span12" style="margin-left:0px; margin-bottom:10px;">
<legend style="color:#ee8929; font-size:16px;">Product List</legend>
<div class="row-fluid">
<table class="table table-striped table-hover" id="mytable">
<thead>
<tr >
<th>
Section Name
</th>
<th>
Section Code
</th>
</tr>
</thead>
<tbody id="tbody">
#foreach (var item in ViewBag.ProductList)
{
<tr id="tableRow" >
<td >
#item.SectionName
</td>
<td >
#item.SectionCode
</td>
<td id="editRow" >
Edit
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="span11" >
<div class="span3"> Order Date : #System.DateTime.Now.ToShortDateString()</div>
<div class="span9" style="text-align:right">
<button type="button" class="btn btn-primary" id="btnDispatch" >Dispatch</button>
<input class="btn btn-default" value="Back" style="width:40px;" onclick="window.location.href='#Url.Action("index") '"/>
</div>
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('.editClass').click(function () {
$('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="btnClose1"> × </button><h5 id="dataConfirmLabel">Edit </h5> </div><div class="modal-body" ><html><table style="width:530px"><tr> <th style="width:120px">Bundle Size</th><th>Count</th><th>Dispatch</th> <th> Pieces</th> </tr><tr> <td><div id="bundleSize1" >60 </div></td> <td><div id="count1">3</div></td> <td><input id="dispatchValue1" type="text" style="width:100px ;height:15px ;margin:1px" /></td> <td> <input id="pieces1" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr> <td><div id="bundleSize2" >10</div></td> <td><div id="count2">8</div></td><td><input id="dispatchValue2" type="text" style="width:100px ;height:15px ;margin:1px" /></td><td> <input id="pieces2" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr style="border-bottom:solid #e8eef4 thick;"> <td><div id="bundleSize3" >1</div></td><td><div id="count3">20</div></td><td><input id="dispatchValue3" type="text" style="width:100px ;height:15px ;margin:1px" /></td><td> <input id="pieces3" class="txt" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr> <td colspan="3" style ="text-align: right; border-right:solid white;"> Total</td> <td> <input id="total" type="text" value="0" style="width:100px ;height:15px ;margin:1px" disabled /></td></tr></table> </html></div> <div class="modal-footer"><button type="button" id="btnOk1" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" >OK</button> <button type="button" id="btnCancel1" class="btn btn-default" data-dismiss="modal" aria-hidden="true" >Cancel</button> </div></div> ');
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmModal').modal({ show: true });
});
$('body').on('click', '#btnOk1', function() {
});
$('body').on('click', '#btnCancel1', function() {
var url="#Url.Action("DispatchNow")";
$(location).attr('href', url);
});
$('body').on('click', '#btnClose1', function() {
var url="#Url.Action("DispatchNow")";
$(location).attr('href', url);
});
Below is the Blur event of textbox, where calculation take place. calculation is ok...but value dont assigned to Pieces textbox.
$('body').on('blur', '#dispatchValue1', function() {
var dispatchValue = $('#dispatchValue1').val();
var bundleSize = $('#bundleSize1').text();
var nPieces1 = dispatchValue*bundleSize;
$('#pieces1').val(nPieces1);
var ntotal= $('#total').text();
$('#supplyQuantity').val(sum);
if(ntotal > 0)
{
var ntotal = $('#total').val();
var sum = parseFloat(ntotal) +parseFloat(nPieces1);
$('#pieces1').val(sum);
$('#total').val(sum);
$('#supplyQuantity').val(sum);
}
else
{
var sum = parseFloat(nPieces1);
$('#pieces1').val(sum);
$('#total').val(sum);
$('#supplyQuantity').val(sum);
}
});
});
$(document).ready(function () {
$('#btnDispatch').click(function () {
$('body').append('<div id="dataConfirmModal1" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="btnClose"> × </button> <h5 id="dataConfirmLabel">Dispatch Alert</h5> </div><div class="modal-body"><h5>This order is dispatched.</h5><br/></div><div class="modal-footer"><button type="button" id="btnOk" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" >OK</button> </div></div> <div class="modal-backdrop"></div>');
$('#dataConfirmModal1').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmModal1').modal({ show: true });
});
$('body').on('click', '#btnOk', function() {
var url="#Url.Action("index")";
$(location).attr('href', url);
});
$('body').on('click', '#btnClose', function() {
var url="#Url.Action("index")";
$(location).attr('href', url);
});
});
</script>
Can you please call alert in this code block;
$('body').on('blur', '#dispatchValue1', function() {
var dispatchValue = $('#dispatchValue1').val();
alert(dispatchValue );
var bundleSize = $('#bundleSize1').text();
alert(bundleSize);
var nPieces1 = dispatchValue*bundleSize;
$('#pieces1').val(nPieces1);
I think at second time one of that alert values is null or empty. Check that please. You lose the control of that field.

How to open the same jQuery Dialog from dynamically and non-dynamically created controls

I need to open the same jQuery dialog from different input text controls (including those that have been created dynamically)
This is what my page displays when it loads for the first time.
When the user presses the "Add" button a new row is added to the table
So far so good. The problem comes when I have to open the dialog that will let users enter text into the inputs ( the dialog will display upon clicking on them)
At first , I thought it would only be necessary to add a class to all the controls and then using the class selector just call the dialog.
Unfortunately then I learned that with dynamic controls you have to use ".on" to attach them events.
Once overcome these difficulties , I run into one more that I haven't been able to solve yet. This is that if you don't want the dialog to be automatically open upon initialization, you have to set "autoOpen" to false. I did so but the only result I got was that none on the inputs worked.
I have also tried putting all the code ,regarding the dialog, into a function and then calling that function when an input is clicked
I did also try declaring a variable and setting that variable to the dialog , something like this:
var dialog= $( "#dialog" )
But it didn't work either
I have tried some possibles solutions , but no luck as of yet.
EDIT : Here's a fiddle so you can have a better idea of what I'm talking about:
http://jsfiddle.net/3BXJp/
Full screen result: http://jsfiddle.net/3BXJp/embedded/result/
Here is the html code for the aspx page (Default.aspx):
<form id="form1" runat="server">
<div>
<fieldset>
<legend>Expression Builder</legend>
<table id="myTable" class="order-list">
<thead>
<tr>
<td colspan="2">
</td>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">
IF(<input type="text" name="condition1" class="showDialog" />
:
</td>
<td>
<input type="text" name="trueValue" class="showDialog" />
)
</td>
<td>
<a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" id="addrow" value="+ Add" />
</td>
</tr>
<tr>
<td colspan="">
ELSE (
<input type="text" name="else" id="else" class="showDialog" />)
</td>
</tr>
</tfoot>
</table>
</fieldset>
<br />
<input type="button" id="btnEnviar" value="Send" />
</div>
<div id="dialog-form" title="Add New Detail">
<p>
All the fields are required.</p>
<table>
<tr>
<td>
<label for="condition" id="lblcondition">
Condition</label>
</td>
<td>
<input type="text" name="condition" id="condition" class="text ui-widget-content ui-corner-all" />
</td>
</tr>
<tr>
<td>
<label for="returnValue" id="lblreturnValue">
Return Value</label>
</td>
<td>
<input type="text" name="returnValue" id="returnValue" class="text ui-widget-content ui-corner-all" />
</td>
</tr>
</table>
</div>
</form>
and here is the javascript code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$("button, input:submit, input:button").button();
$('input:text').addClass("ui-widget ui-state-default ui-corner-all");
var NewDialog = $("#dialog-form");
NewDialog.dialog({ autoOpen: false });
var Ventana = $("#dialog-form");
$("#addrow").on("click", function () {
var counter = $('#myTable tr').length - 2;
$("#ibtnDel").on("click", function () {
counter = -1
});
var newRow = $("<tr>");
var cols = "";
cols += '<td>ELSE IF(<input type="text" name="condition' + counter + '" class="showDialog1" /> </td>';
cols += '<td>: <input type="text" name="TrueValue' + counter + '" class="showDialog1" />)</td>';
cols += '<td><input type="button" id="ibtnDel" value="-Remove"></td>';
newRow.append(cols);
var txtCondi = newRow.find('input[name^="condition"]');
var txtVarlorV = newRow.find('input[name^="TrueValue"]');
newRow.find('input[class ="showDialog1"]').on("click", function () {
//Seleccionar la fila
$(this).closest("tr").siblings().removeClass("selectedRow");
$(this).parents("tr").toggleClass("selectedRow", this.clicked);
Ventana.dialog({
autoOpen: true,
modal: true,
height: 400,
width: 400,
title: "Builder",
buttons: {
"Add": function () {
txtCondi.val($("#condition").val());
txtVarlorV.val($("#returnValue").val());
$("#condition").val("");
$("#returnValue").val("");
$(this).dialog("destroy");
},
Cancel: function () {
//dialogFormValidator.resetForm();
$(this).dialog("destroy")
}
},
close: function () {
$("#condition").val("");
$("#returnValue").val("");
$(this).dialog("destroy")
}
});
return false;
});
$("table.order-list").append(newRow);
counter++;
$("button, input:submit, input:button").button();
$('input:text').addClass("ui-widget ui-state-default ui-corner-all");
});
$("table.order-list").on("click", "#ibtnDel", function (event) {
$(this).closest("tr").remove();
});
$("#btnEnviar").click(function () {
//Armo el objeto que servira de parametro, para ello utilizo una libreria JSON
//Este parametro mapeara con el definido en el WebService
var params = new Object();
params.Expresiones = armaObjeto();
$.ajax({
type: "POST",
url: "Default.aspx/Mostrar",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
loadMenuVar(data);
}
},
error: function (request, status, error) {
alert(jQuery.parseJSON(request.responseText).Message);
}
});
});
$(".showDialog").click(function () {
Ventana.dialog({
autoOpen: true,
modal: true,
height: 400,
width: 400,
title: "Constructor",
buttons: [
{ text: "Submit", click: function () { doSomething() } },
{ text: "Cancel", click: function () { $(this).dialog("destroy") } }
],
close: function () {
$(this).dialog("option", "autoOpen", false);
$(this).dialog("destroy")
}
});
return false;
});
});
This is the closest I've been able to get to the solution, but still can't get the dialog to remain hidden until a input is clicked
Any advise or guidance would be greatly appreciated.
P.S. Sorry for my bad english
I suspect it's because you're using destroy() rather than close() on the dialog. At the moment it looks like you're creating and destroying the dialog each time, don't do that. You should create the dialog once, isolate the dialog functionality to a separate function, and then just use open() and close() on it (you'll have to do some extra work to get the values into the right fields).
You can make your current code work if you style the dialog as hidden it'll stop happening, add this to your HTML (in the <HEAD>):
<style>
#dialog-form {
display: none;
}
</style>
you should probably have a separate style-sheet file you include that has that style in it. Similarly you should put all your JS in a separate file if it isn't already.
But I'd definitely look at re-writing the whole thing to follow the guidelines above, it does look like it can be made a lot simpler which makes it easier to support in the future.
EDIT
This is a simplified version that shows how I would do it.
Script:
var counter = 1; // Counter for number of rows
var currentRow = null; // Current row selected when dialog is active
// Create the dialog
$("#dialog-form").dialog({
autoOpen: false,
dialogClass: "no-close", // Hide the 'x' to force the user to use the buttons
height: 400,
width: 400,
title: "Builder",
buttons: {
"OK": function(e) {
var currentElem = $("#"+currentRow); // Get the current element
currentElem.val($("#d_input").val()); // Copy dialog value to currentRow
$("#d_input").val(""); // Clear old value
$("#dialog-form").dialog('close');
},
"Cancel": function(e) {
$("#d_input").val(""); // Clear old value
$("#dialog-form").dialog('close');
}
}
});
// This function adds the dialog functionality to an element
function addDialog(elemId) {
elem = $("#"+elemId);
elem.on('click', function() {
currentRow = $(this).attr('id');
$("#dialog-form").dialog('open');
});
}
// Add functionality to the 'add' button
$("#addRow").on('click', function () {
counter = counter + 1;
var newId = "in"+counter;
var newRow = "<tr><td><input id='"+newId+"' class='showDialog'></td></tr>";
$('TBODY').append(newRow);
// add the dialog to the new element
addDialog(newId);
});
// add the dialog to the first row
addDialog("in1");
HTML:
<div>
<fieldset>
<legend>Expression Builder</legend>
<table id="myTable" class="order-list">
<tbody><tr>
<td><input id='in1' class='showDialog'></td>
</tr>
</tbody>
</table>
<input type='button' id='addRow' value='add'></input>
</fieldset>
<br />
<input type="button" id="btnEnviar" value="Send" />
</div>
<div id="dialog-form" title="Add New Detail">
<input type="text" id="d_input" />
</div>
Fiddle
This isolates the different functionality into different functions. You can easily expand it to do what you want. If you want the remove functionality I'd consider having a remove button for every row with a given class with a trigger function that removes that row (and the button). Then have a separate count of active rows. At the start use disable() to disable the single button, when you add a row enable() all the buttons of that class. When you remove a row then disable the buttons is existingRows <= 1.

Pass filename as parameter to Controller through jQuery

I am trying to upload an image using jQuery-ui dialog and pass the image file to the controller which will actually do the uploading work. However, I can't seem to get it right. The code is given below
View:
<table>
<tr>
<th>
Image
</th>
<th>
Name
</th>
</tr>
#foreach (var item in Model.CourseApplicationForms)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.thumbnail)
</td>
<td>
#Html.DisplayFor(modelItem => item.sname)
</td>
<td>
Upload File
</td>
</tr>
}
</table>
<div id="dialog" title="Upload files">
#using(Html.BeginForm("ImageUpload","Student", FormMethod.Post, new {id="photouploadform", enctype = "multipart/form-data" }))
{
<p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p><br />
<p><input type="submit" value="Upload file" /></p>
<input type="hidden" id="EnrollId" />
}
</div>
<script type="text/javascript">
$(function () {
$('.photoupload').click(function (event) {
$('#EnrollId').val(event.target.id);
$('#dialog').dialog('open');
});
$('#photouploadform').submit(function () {
$.getJSON("/Student/ImageUpload/", {
Id: $('#EnrollId').val(), file: $('#fileUpload')
}, function (data) {
$('#dialog').append('<p>' + data + '</p>');
});
return false;
});
$("#dialog").dialog({
autoOpen: false,
show: "blind",
width: 400,
hide: "fade",
modal: true,
resizable: false
});
});
</script>
Controller
[AcceptVerbs(HttpVerbs.Get)]
JsonResult ImageUpload(int Id, HttpPostedFileBase file = null)
{
string filePath = string.Empty;
if (file.ContentLength > 0)
{
Directory.CreateDirectory(HttpContext.Server.MapPath("~/Content/Photo/medium"));
filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Photo/medium"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
I want to pass the fileupload image but don't have a clue how to do it. Kindly help
Thanks in advance

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