How to post back selected checkboxes to Controller - asp.net-mvc

I have following view
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Tables <%=ViewData["RetriverName"] %></h2>
<%using (Html.BeginForm("ResfreshSelectedTables", "Home"))
{ // begin form%>
<table id="MyTable">
<thread>
<tr>
<th style="width: 150px; text-align:center"><input type="checkbox" id="SelectAll" />Select All..</th>
</tr>
<tr>
<th style="width:20px; text-align:right">ID</th>
<th style="width:40px">Base Table</th>
<th style="width:50px">Table</th>
<th style="width:280px">Description</th>
</tr>
</thread>
<tbody>
<% int i = 0;
foreach (var item in Model)
{ %>
<tr id="row<%= i.ToString() %>">
<td align="center" style="padding: 0 0 0 0">
<%= Html.CheckBox("selections[" + i.ToString() + "].IsSelected", item.IsSelected)%>
<%= Html.Hidden("selections[" + i.ToString() + "].ID", item.id)%>
<%= Html.Hidden("selections[" + i.ToString() + "].BaseTable", item.baseTable)%>
<%= Html.Hidden("selections[" + i.ToString() + "].Name", item.NAME)%>
</td>
<td style="text-align:right"><%=Html.Encode(item.id)%></td>
<td><%= Html.Encode(item.baseTable)%></td>
<td><%=Html.Encode(item.NAME)%></td>
<td><%=Html.Encode(item.Description) %></td>
</tr>
<% i++;
} %>
</tbody>
</table>
<p>
<input type="submit" value="saving" />
</p>
<% }//end form %>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Select All Checkboxes
$(document).ready(function() {
$('#SelectAll').click(function() {
var newValue = this.checked;
$('input:checkbox').not('input:hidden').each(function() {
// alert(this.id+newValue );
this.checked = newValue;
});
});
});
</script>
</asp:Content>
How do I postback selected checkboxes to the controller ?

Try adding a hidden field for the index of the selected item, as shown in one of Phil Haack's blog posts. You'd then receive the collection as a list of that type on the controller. This will ensure that the collection gets items with both the checked and unchecked checkboxes, in the correct order on the server side. Filter the list to choose only those with IsSelected having value true.
<%= Html.Hidden("selections.Index", i) %>

Related

retrieving data from database using id and displaying it in view in mvc

My problem is in view...Please give me new view which suits my database and action.
My details table:
Passing request id using html action link:
#Html.ActionLink(item.Request_ID, "Details",new { requestid = item.Request_ID },null )
clicking on the link we should get details corresponding to the link from database.
Action method:
public ActionResult Details(string requestid)
{
var entities = new EmployDBEntities1();
var detailsModel = entities.Details.Single(e => e.Id == requestid);
return View(detailsModel);
//return View(entities.Details.ToList());
}
Hope my problem is returning view and designing view. My requirement is I want details for particular id and should display them in the below designed view. I am able to check the ids in var details model and then I have to read remaining fields from databse and disply the fields in my view.I am notable to do it. Please help me.
View:
model IEnumerable<Approvals.Models.Detail>
#{
ViewBag.Title = "Details";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Header {
#Html.ActionLink("Back", "PendingRequests", "Account", null, new { data_icon = "arrow-l", data_rel = "back" })
<h1>#ViewBag.Title</h1>
#Html.ActionLink("Log Off", "LogOff")
}
<head>
<link href="~/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<div data-role="collapsible" data-theme="b" data-content-theme="b">
<h3>Employee Details</h3>
<table class="td3">
#foreach (var item in Model) {
<tr>
<td>Employee ID</td>
<td>#Html.Encode(item.EmpID)</td>
</tr>
<tr>
<td>Short ID</td>
<td>
#Html.Encode(item.ShortID)
</td>
</tr>
<tr>
<td>Grade</td>
<td>#Html.Encode(item.Grade)</td>
</tr>
<tr>
<td>Vertical</td>
<td>#Html.Encode(item.Vertical)</td>
</tr>
<tr>
<td>Vertical Head</td>
<td>#Html.Encode(item.VerticalHead)</td>
</tr>
<tr>
<td>L1 Manager</td>
<td>#Html.Encode(item.L1_Manager)</td>
</tr>
<tr>
<td>L2 Manager</td>
<td>#Html.Encode(item.L2_Mnager)</td>
</tr>
<tr>
<td>CostCentre</td>
<td>#Html.Encode(item.CostCentre)</td>
</tr>
}
</table>
</div>
model Approvals.Models.Detail
#{
ViewBag.Title = "Details";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Header {
#Html.ActionLink("Back", "PendingRequests", "Account", null, new { data_icon = "arrow-l", data_rel = "back" })
<h1>#ViewBag.Title</h1>
#Html.ActionLink("Log Off", "LogOff")
}
<head>
<link href="~/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<div data-role="collapsible" data-theme="b" data-content-theme="b">
<h3>Employee Details</h3>
<table class="td3">
<tr>
<td>Employee ID</td>
<td>#Html.Encode(Model.EmpID)</td>
</tr>
<tr>
<td>Short ID</td>
<td>
#Html.Encode(Model.ShortID)
</td>
</tr>
<tr>
<td>Grade</td>
<td>#Html.Encode(Model.Grade)</td>
</tr>
<tr>
<td>Vertical</td>
<td>#Html.Encode(Model.Vertical)</td>
</tr>
<tr>
<td>Vertical Head</td>
<td>#Html.Encode(Model.VerticalHead)</td>
</tr>
<tr>
<td>L1 Manager</td>
<td>#Html.Encode(Model.L1_Manager)</td>
</tr>
<tr>
<td>L2 Manager</td>
<td>#Html.Encode(Model.L2_Mnager)</td>
</tr>
<tr>
<td>CostCentre</td>
<td>#Html.Encode(Model.CostCentre)</td>
</tr>
</table>
</div>
Instead of var type for detailsModel object give type what is bound to view i.e. IEnumerable of Approvals.Models.Detail in "Details" action.
your view name should match action name if not supplied in return View(). else return View("xxx", detailsModel ) in "Details" action.

I cannot workout how to use a Partial View in a form that uses Knockout in MVC

This is my view;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<SHP.Models.TrainingListEmployeesViewModel>" %>
<%# Import Namespace="System.Web.Script.Serialization" %>
<%# Import Namespace="SHP.Helpers" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Bulk Training
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form class="employeeListEditor" data-bind="submit: save">
<fieldset>
<legend>Allocate or cancel training for the selected employees</legend>
<table>
<tr>
<td style="text-align: right;">Course Name</td>
<td><%: Html.EditorFor(model => model.TrainingName)%></td>
</tr>
<tr>
<td style="text-align: right;">Description (optional)</td>
<td><%:
Html.TextAreaFor(
model => model.TrainingDescription, new { maxlength = "255", style = "width:400px;height:100px;" })%></td>
</tr>
</table>
<%: Html.EditorFor(model => model.ClientEmployeeSelector)%>
<button id="btnAdd" data-bind="click: addEmployee">Add</button><button data-bind="click: clearEmployee">Clear</button>
<div id="displayEmployees" style="margin-top:10px;" data-bind="visible: employees().length > 0">
<table id="employeeDataTable" class="groupBorder">
<thead>
<tr>
<th></th>
<th>Employee</th>
</tr>
</thead>
<tbody data-bind="foreach: employees">
<tr>
<td>
Remove
<input type="hidden" data-bind="value: SearchTextId"/>
</td>
<td><span data-bind="text: SearchText"></span></td>
</tr>
</tbody>
</table>
</div>
<div id="employeeCalendar">
<% if(Model.Cvm != null)
{%>
<% Html.RenderPartial("Calendar", Model.Cvm); %>
<div><span style="margin-top: 10px"></span></div>
<div style="margin-top:20px;">
<div style="display: inline; margin-right:20px; padding:5px;">
<%:Html.MakePopupForm<SHP.Controllers.LeaveController>(o => o.TrainingSingleDate(), refreshOnSuccess: true)%>
<%:Html.PopupFormActionLink<SHP.Controllers.LeaveController>(o => o.TrainingSingleDate(), "Add a single date")%>
</div>
</div>
<% if (TempData["SuccessMessage"].ToSafeString().Length > 0)
{%>
<p class="success" style="padding-top: 20px;"><%: TempData["SuccessMessage"].ToSafeString() %></p>
<% } %>
<% }%>
</div>
</fieldset>
</form>
<script type="text/javascript">
function Employee(id, text) {
var self = this;
self.SearchTextId = ko.observable(id);
self.SearchText = ko.observable(text);
}
$(document).ready(function () {
$('#SearchText').attr("data-bind", "value: autocompleteSearchText");
$('#SearchTextId').attr("data-bind", "value: autocompleteSearchTextId");
$("#TrainingName").attr("data-bind", "value: trainingName");
$("#TrainingDescription").attr("data-bind", "value: trainingDescription");
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
var autocompleteData = { "autocompleteSearchTextId": 0, "autocompleteSearchText": null };
function viewModel() {
var self = this;
self.employees = ko.observableArray(initialData.EmployeeList);
self.trainingName = ko.observable(initialData.TrainingName);
self.trainingDescription = ko.observable(initialData.TrainingDescription);
self.autocompleteSearchText = ko.observable(autocompleteData.autocompleteSearchText);
self.autocompleteSearchTextId = ko.observable(autocompleteData.autocompleteSearchTextId);
self.removeEmployee = function(employee) {
$("#btnAdd").after("<span class='error'>Please wait for calendar update ...</span>");
self.employees.remove(employee);
self.save();
};
self.clearEmployee = function() {
self.autocompleteSearchText('');
};
self.addEmployee = function() {
$("#btnAdd").after("<span class='error'>Please wait for calendar update ...</span>");
self.employees.push(new Employee(self.autocompleteSearchTextId(), self.autocompleteSearchText()));
self.autocompleteSearchText('');
self.save();
};
self.save = function() {
var list = ko.toJS(self.employees);
var name = ko.toJS(self.trainingName);
var description = ko.toJS(self.trainingDescription);
ko.utils.postJson(location.href, { employees: list, trainingName: name, trainingDescription: description });
};
}
ko.applyBindings(new viewModel());
});
</script>
</asp:Content>
You may notice I have a popup form in this view.
Also I would like to put all the code in the employeeCalendar div in a partial view.
Because of the popup window, I have to make sure in my controller that I redirect my Post method to my Get method so that when the popup data input has been completed and undates this view, I do not get an unwanted resend message from windows.
The problem with doing these redirects is that I get a full page postback that looks unpleasent. So I would prefer to refresh my claendar from a partial view via Ajax.
So how do I do this?
This is my controller
[HttpGet]
[Authorize(Roles = "Administrator, Trainer, ManagerAccounts, ManagerIT")]
public ActionResult BulkTraining()
{
if (SessionObjects.Tlevm == null)
{
return this.View(new TrainingListEmployeesViewModel());
}
return this.View(new TrainingListEmployeesViewModel(
SessionObjects.Tlevm.EmployeeList,
SessionObjects.TrainingName,
SessionObjects.TrainingDescription));
}
[HttpPost]
[Authorize(Roles = "Administrator, Trainer, ManagerAccounts, ManagerIT")]
public ActionResult BulkTraining([FromJson] IEnumerable<ClientEmployeeSelector> employees, string trainingName, string trainingDescription)
{
// Items stored in Session used when saving the training dates for the employee
// via the popup window
SessionObjects.TrainingName = trainingName.JsonTrim();
SessionObjects.TrainingDescription = trainingDescription.JsonTrim();
SessionObjects.EmployeeIdList = employees.Select(x => x.SearchTextId).ToList();
SessionObjects.EmployeeNameList = SessionObjects.EmployeeIdList.Count > 0
? Employee.GetNameList(SessionObjects.EmployeeIdList)
: string.Empty;
SessionObjects.Tlevm = new TrainingListEmployeesViewModel(
employees.ToList(),
SessionObjects.TrainingName,
SessionObjects.TrainingDescription);
return this.RedirectToAction("BulkTraining");
}

MVC drop down list that controls a grid - what is the best way to get this to work?

I have a drop down list on the client side. When the user makes a selection, my jquery script extracts the new value of the selection.
But the code below does not work because I cannot work out how to send the selected value back to the controller. I am not sure about the syntax of sending the parameters as I am using paging parameters as it is. Maybe I should do an Ajax call instead?
The View looks like;
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
BankHoliday
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">
<% using (Html.BeginForm())
{%>
<%: Html.AntiForgeryToken() %>
<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><td colspan="3"><i>You can find the bank holiday dates on this <a target="_blank" href="http://www.year-planner-calendar.wanadoo.co.uk/">website</a>.</i> </td></tr>
<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="Save"/>
</td>
</tr>
<% if (ViewData["UpdatedFlag"] == "True")
{ %>
<tr>
<td id="confirmationMessage" colspan="3">
At time <% Response.Write(DateTime.Now.ToString("T")); %> - Details have been successfully saved
</td>
</tr>
<%}
else if (ViewData["UpdatedFlag"] == "False")
{%>
<tr>
<td id="Td1" colspan="3">
At time <% Response.Write(DateTime.Now.ToString("T")); %> - ERROR! Details have NOT been saved
</td>
</tr>
<%} %>
</table>
</fieldset>
<% } %>
<script language="javascript" type="text/javascript">
$(function () {
$("#SelectedYear").change(function () {
var year = $("#SelectedYear").val();
$("#wholepage").load("/BankHoliday/Create/" + year);
});
});
</script>
</asp:Content>
and the Controller looks like;
public ActionResult ListHistory(GridSortOptions sort, int? page, int? EmployeeStatusId)
{
if (Request.QueryString["lastPersonMessage"] == null)
ViewData["LastPersonMessage"] = string.Empty;
else
ViewData["LastPersonMessage"] = Request.QueryString["lastPersonMessage"];
IEnumerable<EmployeeExtended> employees = null;
switch (EmployeeStatusId.GetValueOrDefault(1))
{
case 1: employees = EmployeeExtended.GetAllFormerEmployees();
break;
case 2: employees = EmployeeExtended.GetAllOnNoticeEmployees();
break;
case 3: employees = EmployeeExtended.GetAllCurrentEmployees();
break;
}
if (sort.Column != null)
{
employees = employees.OrderBy(sort.Column, sort.Direction);
}
int pageLength = Convert.ToInt32(ConfigurationManager.AppSettings["EmployeeListPageLength"].ToString());
employees = employees.AsPagination(page ?? 1, pageLength);
ViewData["sort"] = sort;
return View(employees);
}
You can it inside an Ajax.BeginForm() Call but the Url wouldn't change then.. - means: every time you refresh it, it'll return you back to the default page..
I already did something very similar to this:
<%: Html.DropDownList(Model => Model.SelectedYear, Model.YearList, new { onchange = "location.href='/Controller/Action/'+this.value" }) %>
This should provide some foundation on solving the issue.

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.

submit View in ASP.NET MVC

How submit list View in ASP.NET MVC. List View dont have
input type="submit" value="Save"
and I dont know where to put it.
Problematic code is:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcZezanje.Models.student1>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Studenti
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Studenti</h2>
<table class="data-table">
<tr>
<th>
Br. Indexa
</th>
<th>
Prezime
</th>
<th>
Ime
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.id_stud) %>
</td>
<td>
<%= Html.Encode(item.prezime) %>
</td>
<td>
<%= Html.Encode(item.ime) %>
</td>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
What do you want to submit? This code displays list of students. There is no user input. If there is no user input, there is no need to place submit button. if you want to edit user data, you'll have to do something like:
<form method="post" action="/Students/Save">
<table class="data-table">
<tr>
<th>
Br. Indexa
</th>
<th>
Prezime
</th>
<th>
Ime
</th>
</tr>
<% int i = 0; foreach (var item in Model) { %>
<tr>
<td>
<%= Html.TextBox("students[" + i + "].id_stud", item.id_stud) %>
</td>
<td>
<%= Html.TextBox("students[" + i + "].prezime", item.prezime) %>
</td>
<td>
<%= Html.TextBox("students[" + i + "].ime", item.ime) %>
</td>
</tr>
<% i++;} %>
</table>
<input type="submit" />
</form>
Here you can read about binding to list:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
It has changed a little, you don't have to specify index anymore.

Resources