MVC datepicker in a grid - asp.net-mvc

I am using the following EditorTemplate which ensure the datepicker is enabled for date fields;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%:Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { #class = "datePicker" }) %>
However the date is in the partial view following view;
<fieldset>
<legend>Enter the bank holidays here:</legend>
<table>
<tr>
<th>Bank Holiday</th>
<th>Date</th>
<th>Notes</th>
</tr>
<% foreach (var bankHolidayExtended in Model.BankHolidays)
{ %>
<% Html.RenderPartial("BankHolidaySummary", bankHolidayExtended); %>
<% } %>
<tr>
<td align="center" colspan="3" style="padding-top:20px;"><input type="submit" value="Submit" /></td>
</tr>
</table>
</fieldset>
The partial view looks like this,
<tr>
<td><%: Model.T.BankHolidayDescription%></td>
<td><%: Html.EditorFor(model => model.BH.NullableBankHolidayDate)%></td>
<td><%: Html.EditorFor(model => model.BH.BankHolidayComment)%></td>
</tr>
The problem is that the Date field has the same ID for each row. So when you enter a date on row x, it only updates the date on row 1.
How do I fix this so that I update the correct row?

Can you do something like this :
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BankHolidays>" %> <%:Html.TextBox("", (Model.HasValue ? Model.NullableBankHolidayDate.ToShortDateString() : string.Empty), new { #class = "datePicker" id = Model.BankID }) %>
And instead sending the editor just Date, you sent him Model with date and bankID :
<td><%: Html.EditorFor(model => model.BH)%></td>
I assume that you have some sort of ID's in your BANK holiday (bankID,bankHolidayID) model. Sorry, I'm not so good at ASP.NET MVC..

Related

I have just inserted a item of data. Now I want my view to clear, but it doesn't

I use my View to added a record in a database table.
After I click submit, I want the screen to clear ready for my next insert.
So within my controller I send a new ViewModel with the default values for both my HttpGet and HttpPost.
However I am finding that once I have inserted a record, all the old values remain after my HttpPost.
What am I doing wrong?
[HttpGet]
[Authorize(Roles = "Administrator, AdminAccounts")]
public ActionResult Add()
{
ViewData["LastPerson"] = string.Empty;
return View(new EmployeeViewModel());
}
[HttpPost]
[Authorize(Roles = "Administrator, AdminAccounts")]
public ActionResult Add(Employee employee)
{
if (ModelState.IsValid)
{
var employeeViewModel = new EmployeeViewModel();
ViewData["LastPerson"] = string.Format("{0} {1} {2}", employee.Forename, employee.Middlenames,
employee.Surname);
employeeViewModel.Employee = employee;
employeeViewModel.Employee.Add();
}
return View(new EmployeeViewModel());
}
My view looks like this;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master"
Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.EmployeeViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Add
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">
<% using (Html.BeginForm("Add", "Employee")) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Add Employee</legend>
<table>
<tr>
<td align="right">
<%: Html.LabelFor(model => model.Employee.UserName)%>
</td>
<td>
<%: Html.EditorFor(model => model.Employee.UserName)%>
<%: Html.ValidationMessageFor(model => model.Employee.UserName)%>
</td>
</tr>
<tr>
<td align="right">
<%: Html.LabelFor(model => model.Division.DivisionId) %>
</td>
<td>
<%: Html.DropDownListFor(model => model.Division.DivisionId, Model.DivisionSelectList, "<--Select-->")%>
<%: Html.ValidationMessageFor(model => model.Division.DivisionId)%>
</td>
</tr>
<tr>
<td align="right">
<%: Html.LabelFor(model => model.Department.DepartmentId) %>
</td>
<td>
<%: Html.DropDownListFor(model => model.Department.DepartmentId, Model.DepartmentSelectList, "<--Select-->")%>
<%: Html.ValidationMessageFor(model => model.Department.DepartmentId) %>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="padding-top:20px;">
<input type="submit" value="Save" /></td>
</tr>
</table>
<% if (ViewData["LastPerson"].ToString().Length > 0)
{ %>
<p>
At time <% Response.Write(DateTime.Now.ToString("T")); %>
- You have just entered <%Response.Write(ViewData["LastPerson"].ToString()); %>.
</p>
<%} %>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
<script language="javascript" type="text/javascript">
//Hook onto the DivisionId list's onchange event
$("#Division_DivisionId").change(function () {
//build the request url
var url = '<%: Url.Content("~/")%>' + "Employee/GetDepartments";
//fire off the request, passing it the id which is the DivisionId's selected item value
$.getJSON(url, { divisionId: $("#Division_DivisionId").val() }, function (data) {
//Clear the Department list
$("#Department_DepartmentId").empty();
$("#Department_DepartmentId").append("<option><--Select--></option>");
//Foreach Department in the list, add a department option from the data returned
$.each(data, function (index, optionData) {
$("#Department_DepartmentId").append(
"<option value='" + optionData.DepartmentId + "'>" +
optionData.DepartmentName + "</option>");
});
});
}).change();
</script>
ModelState can surprise you with the data it ends up remembering. However, in your case, you should just redirect to your blank page, rather than returning the View(model) directly:
return RedirectToAction("Add");
Instead of:
return View(new EmployeeViewModel());
After submitting the form, what happens if the user refreshes the browser? With your design, it will re-postback the form data, which isn't good. A redirect will solve that problem. See here for more info: http://en.wikipedia.org/wiki/Post/Redirect/Get.

Model binding when rendering a partial view multiple times (partial view used for editing)

Greeting Everyone,
I'm having a little trouble with a partial view I'm using as an edit form. Aside from the hidden elements in the form, the model is null when passed to my EditContact post controller.
I should add, I realize there's a more seamless way to do what I'm doing using AJAX, but I think if I can solve the clunky way first it will help me understand the framcework a little better.
Here's my EditContact partial view:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WebUI.DataAccess.CONTACT>" %>
<div id="contactPartial-<%= ViewData.Model.id %>">
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("EditContact", "Investigator"))
{ %>
<%= Html.HiddenFor(Model => Model.id) %>
<%= Html.HiddenFor(Model => Model.investId) %>
<table id="EditContact-<%= ViewData.Model.id %>" width="100%">
<tr>
<th colspan="4">
<b>New Contact</b>
</th>
</tr>
<tr>
<td>
<b>
<%= Html.LabelFor(Model => Model.type)%></b><br />
<%= Html.EditorFor(Model => Model.type, null, "contactType-" + ViewData.Model.id)%><br />
<%= Html.ValidationMessageFor(Model => Model.type) %>
</td>
</tr>
<tr>
<td>
<b>
<%= Html.LabelFor(Model => Model.salutation)%></b><br />
<%= Html.EditorFor(Model => Model.salutation, null, "contactsalutation-"+ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.firstName)%></b><br />
<%= Html.EditorFor(Model => Model.firstName, null, "contactFirstName-"+ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.middleName)%></b><br />
<%= Html.EditorFor(Model => Model.middleName, null, "contactMiddleName-"+ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.lastName)%></b><br />
<%= Html.EditorFor(Model => Model.lastName, null, "contactLastName-"+ViewData.Model.id)%><br />
<%= Html.ValidationMessageFor(Model => Model.lastName)%>
</td>
</tr>
<tr>
<td>
<b>
<%= Html.LabelFor(Model => Model.title)%></b><br />
<%= Html.EditorFor(Model => Model.title, null, "contactTitle-"+ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.phone)%></b><br />
<%= Html.EditorFor(Model => Model.phone, null, "contactPhone="+ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.altPhone)%></b><br />
<%= Html.EditorFor(Model => Model.altPhone, null, "contactAltPhone-" + ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.fax)%></b><br />
<%= Html.EditorFor(Model => Model.fax, null, "contactFax-" + ViewData.Model.id)%>
</td>
</tr>
<tr>
<td>
<b>
<%= Html.LabelFor(Model => Model.email)%></b><br />
<%= Html.EditorFor(Model => Model.email, null, "contactEmail-" + ViewData.Model.id)%>
</td>
<td>
<b>
<%= Html.LabelFor(Model => Model.comment)%></b><br />
<%= Html.EditorFor(Model => Model.comment, null, "contactComment-" + ViewData.Model.id)%>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Save" />
</td>
<td>
<button id="<%= ViewData.Model.id %>" class="contactEditHide">
Cancel</button>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
<% } %>
</div>
When the Edit contact post controller is passed the model only id and investId have values; everything else is null. Here's how I'm rendering the partial view in my Details view:
<table width="100%">
<tr>
<th colspan="7">
<b>Contacts</b>
</th>
<th id="contactButton" class="button">
<button id="showEditContact-0" type="button" class="contactEditShow">New Contact</button>
</th>
</tr>
<tr>
<th>
Type
</th>
<th>
Name
</th>
<th colspan="2">
Title
</th>
<th>
Prim. & Alt. Phone
</th>
<th>
Fax
</th>
<th colspan="2">
Comment
</th>
</tr>
<% for (int i = 0; i < Model.CONTACTs.Count; i++)
{ %>
<tr id="contactRow-<%= Model.CONTACTs[i].id %>" class="contactRow">
<td>
<%= Html.Encode(Model.CONTACTs[i].type)%>
</td>
<td>
<%= Html.Encode(Model.CONTACTs[i].salutation)%>
<%= Html.Encode(Model.CONTACTs[i].firstName)%>
<%= Html.Encode(Model.CONTACTs[i].middleName)%>
<%= Html.Encode(Model.CONTACTs[i].lastName)%>
<br />
<a href="mailto:<%= Html.AttributeEncode(Model.CONTACTs[i].email) %>">
<%= Html.Encode(Model.CONTACTs[i].email)%></a>
</td>
<td colspan="2">
<%= Html.Encode(Model.CONTACTs[i].title)%>
</td>
<td>
Prim:<%= Html.Encode(Model.CONTACTs[i].phone)%><br />
Alt:<%= Html.Encode(Model.CONTACTs[i].altPhone)%>
</td>
<td>
<%= Html.Encode(Model.CONTACTs[i].fax)%>
</td>
<td>
<%= Html.Encode(Model.CONTACTs[i].comment)%>
</td>
<td>
<button id="<%= Model.CONTACTs[i].id %>" type="button" class="contactEditShow">Edit Contact</button>
</td>
</tr>
<tr>
<td colspan="8">
<% Html.RenderPartial("EditContact", Model.CONTACTs[i]); %>
</td>
</tr>
<% } %>
</table>
My details view is strongly tyed to an INVESTIGATOR model:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<WebUI.DataAccess.INVESTIGATOR>" %>
As you can see above, my partial view is strongly typed to a CONTACTS model.
I ran into a similar problem with Model binding when, in a view, I was trying to allow for the editing all layers of an address at one time and fixed it by indexing the model, similar to the Details view above. It seems like I need to do the same thing in my partial view to ensure Model binding, but I'm not sure how to achieve this (having syntax issues).
Of course, I could be off here an need a new solution in general!
Let me know if you need more detail! Thanks!
Why are you using
<%= Html.EditorFor(Model => Model.salutation, null, "contactsalutation-"+ViewData.Model.id)%>
If you use it simply like this
<%= Html.EditorFor(Model => Model.salutation) %>
It should be working.
In order to map your model, your control need to have the same id as there name, and the third parameter you're using changes your control id.
Use Html.EditorFor instead of Html.RenderPartial.
See Model binding with nested child models and PartialViews in ASP.NET MVC.

JQuery Datepicker for multiple .NET MVC Input Fields not working

I have simplified my work for this question but the same problem remains. I am using the Textbox HTML helper to display empty textboxes as I loop through the items in this model.
<% foreach (var item in Model) { %>
<tr>
<td><%: item.ID %></td>
<td><%: Html.TextBox("usernames", null, new { #class = "datepicker" }) %></td>
<td><%: item.Password %></td>
<td> <%: item.Race %></td>
</tr>
<% } %>
Because I have several rows this produces several fields all with the class "datepicker". I am applying the following JQuery for the datepicker:
$(document).ready(function () {
$('input').filter('.datepicker').datepicker({
dateFormat: "dd/mm/yy",
onSelect: function (value, date) {
alert(this.value);
}
});
});
When the page renders, every textbox creates a calendar as expected but it always puts the date into the textbox on line one. I need the date to go into the textbox the calendar appeared next to. The html for the code above looks fine:
<tr>
<td>6</td>
<td><input class="datepicker" id="usernames" name="usernames" type="text" value="" /></td>
<td>dinosaur</td>
<td> 1</td>
</tr>
Interstingly, if I simply create 4 of class "datepicker" everything is fine. Its the way the html helpers create the for you.
Please Help!
The answer is to give the textboxes being generated unique id's like below otherwise it will not work.
<% foreach (var item in Model) { %>
<tr>
<td><%: item.ID %></td>
<td><%: Html.TextBox("usernames", null, new { ID=item.ID #class = "datepicker" }) %></td>
<td><%: item.Password %></td>
<td> <%: item.Race %></td>
</tr>
<% } %>

ASP.Net MVC 2 - drop down list that controls a grid

I am just starting on MVC so this should be an easy question to answer.
I am using MVC 2 for ASP.Net.
I have a drop down list which when changes should cause the grid to change as well.
I have found a way to catch the change selection event and refresh the whole form using the code below.
The $('#TheForm').submit(); command causes the Index method of the Controller to run, and resets everything back as before.
What I want of course is for this method to pick up the new value of the dropdownlist, extract and display the new data in the View accordingly.
Is this how I should do it, or should I do more on the client side instead?
$(function () {
$("#StatusId").change(function () {
$('#TheForm').submit();
});
});
<p>
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "TheForm" })){%>
<%: Html.DropDownList("StatusId", (SelectList) ViewData["Status"]) %>
<%}%>
</p>
<p>
<% if (Request.IsAuthenticated) { %>
<%: Html.ActionLink("Add new item", "Add") %>
<% } %>
</p>
<table>
<tr>
<th>
Title
</th>
<th>
Date
</th>
<th>
Status
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink(item.Title, "Details", new { id = item.ItemCode }) %>
</td>
<td>
<%: String.Format("{0:g}", item.DateCreated) %>
</td>
<td>
<%: item.Status %>
</td>
</tr>
<% } %>
</table>
<p>
<%: Html.Label("Page: ") %>
<% for (int i = 1; i < Convert.ToInt32(ViewData["NumberOfPages"]); i++)
{ %>
<%: Html.ActionLink(i.ToString(), "Index", new { page = i })%>
<% } %>
</p>
The Index action needs a parameter StatusId.
It has to filter the list of items by StatusId. If this does not work please post the code of the action.

Model binding nested collections in ASP.NET MVC

I'm using Steve Sanderson's BeginCollectionItem helper with ASP.NET MVC 2 to model bind a collection if items.
That works fine, as long as the Model of the collection items does not contain another collection.
I have a model like this:
-Product
--Variants
---IncludedAttributes
Whenever I render and model bind the Variants collection, it works jusst fine. But with the IncludedAttributes collection, I cannot use the BeginCollectionItem helper because the id and names value won't honor the id and names value that was produced for it's parent Variant:
<div class="variant">
<input type="hidden" value="bbd4fdd4-fa22-49f9-8a5e-3ff7e2942126" autocomplete="off" name="Variants.index">
<input type="hidden" value="0" name="Variants[bbd4fdd4-fa22-49f9-8a5e-3ff7e2942126].SlotAmount" id="Variants_bbd4fdd4-fa22-49f9-8a5e-3ff7e2942126__SlotAmount">
<table class="included-attributes">
<input type="hidden" value="0" name="Variants.IncludedAttributes[c5989db5-b1e1-485b-b09d-a9e50dd1d2cb].Id" id="Variants_IncludedAttributes_c5989db5-b1e1-485b-b09d-a9e50dd1d2cb__Id" class="attribute-id">
<tr>
<td>
<input type="hidden" value="0" name="Variants.IncludedAttributes[c5989db5-b1e1-485b-b09d-a9e50dd1d2cb].Id" id="Variants_IncludedAttributes_c5989db5-b1e1-485b-b09d-a9e50dd1d2cb__Id" class="attribute-id">
</td>
</tr>
</table>
</div>
If you look at the name of the first hidden field inside the table, it is Variants.IncludedAttributes - where it should have been Variants[bbd4fdd4-fa22-49f9-8a5e-3ff7e2942126].IncludedAttributes[...]...
That is because when I call BeginCollectionItem the second time (On the IncludedAttributes collection) there's given no information about the item index value of it's parent Variant.
My code for rendering a Variant looks like this:
<div class="product-variant round-content-box grid_6" data-id="<%: Model.AttributeType.Id %>">
<h2><%: Model.AttributeType.AttributeTypeName %></h2>
<div class="box-content">
<% using (Html.BeginCollectionItem("Variants")) { %>
<div class="slot-amount">
<label class="inline" for="slotAmountSelectList"><%: Text.amountOfThisVariant %>:</label>
<select id="slotAmountSelectList"><option value="1">1</option><option value="2">2</option></select>
</div>
<div class="add-values">
<label class="inline" for="txtProductAttributeSearch"><%: Text.addVariantItems %>:</label>
<input type="text" id="txtProductAttributeSearch" class="product-attribute-search" /><span><%: Text.or %> <a class="select-from-list-link" href="#select-from-list" data-id="<%: Model.AttributeType.Id %>"><%: Text.selectFromList.ToLowerInvariant() %></a></span>
<div class="clear"></div>
</div>
<%: Html.HiddenFor(m=>m.SlotAmount) %>
<div class="included-attributes">
<table>
<thead>
<tr>
<th><%: Text.name %></th>
<th style="width: 80px;"><%: Text.price %></th>
<th><%: Text.shipping %></th>
<th style="width: 90px;"><%: Text.image %></th>
</tr>
</thead>
<tbody>
<% for (int i = 0; i < Model.IncludedAttributes.Count; i++) { %>
<tr><%: Html.EditorFor(m => m.IncludedAttributes[i]) %></tr>
<% } %>
</tbody>
</table>
</div>
<% } %>
</div>
</div>
And the code for rendering an IncludedAttribute:
<% using (Html.BeginCollectionItem("Variants.IncludedAttributes")) { %>
<td>
<%: Model.AttributeName %>
<%: Html.HiddenFor(m => m.Id, new { #class = "attribute-id" })%>
<%: Html.HiddenFor(m => m.ProductAttributeTypeId) %>
</td>
<td><%: Model.Price.ToCurrencyString() %></td>
<td><%: Html.DropDownListFor(m => m.RequiredShippingTypeId, AppData.GetShippingTypesSelectListItems(Model.RequiredShippingTypeId)) %></td>
<td><%: Model.ImageId %></td>
<% } %>
As you are using MVC 2 and EditorFor, you shouldn't need to use Steve's solution, which I believe is just a work around for MVC 1. You should just be able to do something like:
<% for (int i = 0; i < Model.Variants.Count; i++) { %>
<%= Html.DisplayFor(m => m.Variants[i].AttributeType.AttributeTypeName) %>
<% for (int j = 0; j < Model.Variants[i].IncludedAttributes.Count; j++) { %>
<%= Html.EditorFor(m => m.Variants[i].IncludedAttributes[j]) %>
<% } %>
<% } %>
Please note that the use of the indexes ...[i]...[j]... is important and is how MVC will know how to render the Id's and names correctly.

Resources