Why don't my form get posted correctly? - asp.net-mvc

I am working on MVC POST/GET requests, but I observed some strange behavior.
My form is posted after editing it by clicking "Save" from browser, but when I received the request, all the attributes were undefined. CourseName, CourseCreditPts, Institute were null or zeros.
Code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(tblCourse a_Course)
{
// Retrieve existing object
var CourseToBeSaved = _pr.FindCourseById(a_Course.CourseID);
// without try-catch exception thrown
try
{
TryUpdateModel(CourseToBeSaved);
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
// Save
_pr.Save();
return View();
}
and the .aspx file containing code:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DataWarehouse.tblCourse>" %>
<%# Import Namespace="DataWarehouse.Helpers" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit Course</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<%: Html.HiddenFor(x=>x.CourseID) %>
<table>
<tr>
<td><b>Institute</b></td>
<td><%: Html.DropDownList("InstituteID")%> <%: Html.ValidationMessageFor(x=>x.InstituteID) %></td>
</tr>
<tr>
<td><b>CourseName</b></td>
<td><%: Html.TextBox("EditAbleCourseName")%> <%: Html.ValidationMessageFor(x => x.CourseName)%></td>
</tr>
<tr>
<td><b>CreditPoints</b></td>
<td><%: Html.TextBox("EditAbleCreditPoints")%> <%: Html.ValidationMessageFor(x => x.CreditPts)%></td>
</tr>
<tr>
<td><b>Status</b></td>
<td><%: Html.DropDownList("EditAbleStatus")%> <%: Html.ValidationMessageFor(x => x.Status)%></td>
</tr>
</table>
<p>
<input type="submit" value="Save" />
</p>
<% } %>
</asp:Content>

You didn’t post how the tblCourse class is defined, but from your validators it seems like it has a property called CourseName. You have named the textbox that should contain the course name EditAbleCourseName and there is your problem. For default model binding you have to name the inputs to the same name as the property on the class. This goes for your other properties too.
So try to rename your inputs to the same name as the properties on your class.
<%: Html.TextBox("CourseName")%>
and so on...

Related

Object reference not set to an instance of an object - Partial View

I have a strongly typed partial view which is giving me "Object reference not set to an instance of an object" error when I launch the master view. I know I am not passing in any parameters yet, but is there a way to handle this error?
Master View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Test Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="partial">
<% Html.RenderPartial("DisplayPartial"); %>
</div>
</asp:Content>
Partial View:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %>
<% foreach (var item in Model) {
if (item == null) continue; %>
<tr>
<td>
<%: item.Item1%>
</td>
<td>
<%: item.Item2%>
</td>
</tr>
<% } %>
</table>
You have to pass some Model to your partialView, because it need a instance of IEnumerable<Student.Models.vwStudent>
<% Html.RenderPartial("DisplayPartial", model); %>
Or, you can check in your partial view if the model is not null.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %>
<% if (Model != null) {
foreach (var item in Model) {
if (item == null) continue; %>
<tr>
<td>
<%: item.Item1%>
</td>
<td>
<%: item.Item2%>
</td>
</tr>
<% }
} %>
</table>
If you need to render this partial view when you don't have a Model, you can certainly test that Model is not null before the foreach loop
if (Model != null)
foreach (...)

MVC Error: model item of type 'System.Collections.Generic.IEnumerable`1 required

I'm doing some modifications to a system, and I've run into an exception that I was hoping someone could help with?? The error I'm getting is the following:
Exception Details:
System.InvalidOperationException: The
model item passed into the dictionary
is of type
'System.Collections.Generic.List1[System.String]',
but this dictionary requires a model
item of type
'System.Collections.Generic.IEnumerable1[MyApp.Data.aspnet_Users]'.
Basically what I want to do is display a list of Inactive users. Here is the controller I've written for that:
public ActionResult InactiveUsers()
{
using (ModelContainer ctn = new ModelContainer())
{
aspnet_Users users = new aspnet_Users();
DateTime duration = DateTime.Now.AddDays(-3);
var inactive = from usrs in ctn.aspnet_Users
where usrs.LastActivityDate <= duration
orderby usrs.LastActivityDate ascending
select usrs.UserName;
return View(inactive.ToList());
}
}
From here then I added a partial view. Here is the code for it if anyone is interested. Just the usual Add View --> List.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Data.aspnet_Users>>" %>
<table>
<tr>
<th></th>
<th>
ApplicationId
</th>
<th>
UserId
</th>
<th>
UserName
</th>
<th>
LoweredUserName
</th>
<th>
MobileAlias
</th>
<th>
IsAnonymous
</th>
<th>
LastActivityDate
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Edit", "Edit", new { id=item.UserId }) %> |
<%: Html.ActionLink("Details", "Details", new { id=item.UserId })%> |
<%: Html.ActionLink("Delete", "Delete", new { id=item.UserId })%>
</td>
<td>
<%: item.ApplicationId %>
</td>
<td>
<%: item.UserId %>
</td>
<td>
<%: item.UserName %>
</td>
<td>
<%: item.LoweredUserName %>
</td>
<td>
<%: item.MobileAlias %>
</td>
<td>
<%: item.IsAnonymous %>
</td>
<td>
<%: String.Format("{0:g}", item.LastActivityDate) %>
</td>
</tr>
<% } %>
</table>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
And for completeness here is the Index page where I render the partial:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Administrator.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<% Html.RenderAction("InactiveUsers"); %>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Header" runat="server">
</asp:Content>
If anyone has any advice I'd be very grateful :)
Hi i think its because in your partial view type is System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Data.aspnet_Users>>
but you select user names
select usrs.UserName;
return View(inactive.ToList());
Try change it to select usrs; but not usrs.UserName

MVC: Form not rendering in partial view

I have a form with tabs. Subordinate to each tab is a partial view.
When the user submits to save changes, I want to call a method for that partial view, so for the partial view I put in <% using (Html.BeginForm(...) %>. But this gets ignored and clicking submit will call the method associated with the container view instead. Why is this, and how do I get this to work?
The View looks like;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Employee.Master" Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.HolidayRequestViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
HolidayRequest
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="EmployeeContent" runat="server">
<% using (Html.BeginForm()) {%>
<%: Html.AntiForgeryToken() %>
<h2>Holiday Request</h2>
<p>You have <%: Html.DisplayFor(model => model.DaysAvailableThisYear) %> days left annual leave for this year
and <%: Html.DisplayFor(model => model.DaysAvailableNextYear) %> days left for next year.</p>
<p>If your request is approved and exceeds the number of days left, then those extra days will not be paid.</p>
<div id="tabs">
<ul>
<li>Approver</li>
<li>Single Date</li>
<li>Date Range</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("GetApproverTab", Model); %>
</div>
<div id="tabs-2">
<% Html.RenderPartial("GetSingleDateTab", Model); %>
</div>
<div id="tabs-3">
<% Html.RenderPartial("GetDateRangeTab", Model); %>
</div>
</div>
<%: Html.HiddenFor(x => x.EmployeeId) %>
<% } %>
</asp:Content>
The partial view looks like;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.WebUI.Models.HolidayRequestViewModel>" %>
<% using (Html.BeginForm("GetSingleDateTab", "Employee", FormMethod.Post, new { id = "frmSingleDate" }))
{ %>
<p>Enter your day or part day of Annual Leave here.</p>
<table>
<tr>
<td align="right">Date:</td>
<td><%: Html.EditorFor(x => x.SingleDate) %></td>
</tr>
<tr>
<td align="right">Morning Only:</td>
<td><%: Html.CheckBoxFor(x => x.MorningOnlyFlag) %></td>
</tr>
<tr>
<td align="right">Afternoon Only:</td>
<td><%: Html.CheckBoxFor(x => x.MorningOnlyFlag) %></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save" /></td>
</tr>
</table>
<% } %>
and the controller looks like;
#region Employee Holiday Request
public ActionResult HolidayRequest()
{
return View(new HolidayRequestViewModel(Employee.GetLoggedInUser().EmployeeId));
}
[HttpPost] // This is the method that gets executed
public ActionResult HolidayRequest(HolidayRequestViewModel hrvm)
{
if (ModelState.IsValid)
{
hrvm.Update();
return View(new HolidayRequestViewModel(hrvm.EmployeeId));
}
return View(hrvm);
}
[HttpPost] // This is the method I want to get executed.
public ActionResult GetSingleDateTab(HolidayRequestViewModel hrvm)
{
if (ModelState.IsValid)
{
hrvm.Update();
return View(new HolidayRequestViewModel(hrvm.EmployeeId));
}
return View("GetSingleDateTab", hrvm);
}
#endregion
You can't have nester forms in html.
I discover an unbelievable solution. Just insert a <script> tag above the <form> tag.
<script type="text/javascript">
// don't remove <script> tag
</script>
<form ....

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.

MVC - fields in a partial View need a Unique Id. How do you do this?

In my view I render a partial view within a loop.
The problem I have is that for each new row, the Id of the fields remains the same.
I can I change this so that the Ids are unique and predictable?
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master" Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.BankHolidayViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
BankHoliday
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">
<% using (Html.BeginForm())
{%>
<h3>Bank Holiday Administration</h3>
<p>Select the year: <%: Html.DropDownListFor(model => model.SelectedYear, Model.YearList)%></p>
<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="Create" />
</td>
</tr>
</table>
</fieldset>
<% } %>
Partial View
" %>
<tr>
<td><%: Model.T.BankHolidayDescription%></td>
<td><%: Html.EditorFor(model => model.BH.NullableBankHolidayDate)%></td>
<td><%: Html.EditorFor(model => model.BH.BankHolidayComment)%></td>
</tr>
I would recommend you using editor templates instead of rendering partial views:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master" Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.BankHolidayViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
BankHoliday
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">
<% using (Html.BeginForm()) { %>
<h3>Bank Holiday Administration</h3>
<p>Select the year: <%: Html.DropDownListFor(model => model.SelectedYear, Model.YearList)%></p>
<fieldset>
<legend>Enter the bank holidays here:</legend>
<table>
<tr>
<th>Bank Holiday</th>
<th>Date</th>
<th>Notes</th>
</tr>
<%: Html.EditorFor(x => x.BankHolidays) %>
<tr>
<td align="center" colspan="3" style="padding-top:20px;">
<input type="submit" value="Create" />
</td>
</tr>
</table>
</fieldset>
<% } %>
</asp:Content>
And then place your user control in ~/Views/Home/EditorTemplates/BankHolidayExtended.ascx (the name and location are important, replace Home with the name of your controller):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.WebUI.Models.BankHolidayExtended>" %>
<tr>
<td><%: Model.T.BankHolidayDescription %></td>
<td><%: Html.EditorFor(model => model.BH.NullableBankHolidayDate) %></td>
<td><%: Html.EditorFor(model => model.BH.BankHolidayComment) %></td>
</tr>
This editor template will be automatically rendered for each element of the BankHolidays collection property on your view model. It will ensure that unique Ids are generated and the name of the input fields will be suitable for binding in the POST action. It also makes your code more readable.

Resources