Returning specific table data from the view to the controller? asp.net MVC - asp.net-mvc

So I have a view which is currently displaying a table of data from the database with a select/selectall checkbox in place. What I'd like to do is be able to get a list of my CustomerNumbers and whether or not they have been checked and return it to my controller for further action.
Below is my how my view is currently written. I have tried numberous ways to get this to work and I am stumped.
#model MassInactiveInspections.Models.CustomerInfoList
<div class="container">
<h2>#ViewBag.Title</h2>
<div class="bs-callout bs-callout-info" style="margin-bottom: 0px;">
</div>
<div class="col-md-8">
#using (Html.BeginForm("SelectedCustomers", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
<table class="table table-bordered">
<tr>
<th class="active">#Html.DisplayName("Select All?")<input type="checkbox" class="select-all checkbox" name="select-all" /></th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().BusinessName)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().CustomerName)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().CustomerNumber)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().InspectionCycleDescription)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().LastInspectionDate)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().RouteCode)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().RouteID)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().SiteNumber)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().SystemCode)</th>
</tr>
#foreach (var item in Model.CustomerInfoListView)
{
<tr>
<td class="active"> <input id="Selected" input type="checkbox" class="select-item checkbox" name="select-item" value="1000" /> </td>
<td>#Html.DisplayFor(modelItem => item.BusinessName)</td>
<td>#Html.DisplayFor(modelItem => item.CustomerName)</td>
<td>
#Html.DisplayFor(modelItem => item.CustomerNumber)
#Html.HiddenFor(m => m.CustomerInfoListView.FirstOrDefault().CustomerNumber)
</td>
<td>#Html.DisplayFor(modelItem => item.InspectionCycleDescription)</td>
<td>#Html.DisplayFor(modelItem => item.LastInspectionDate)</td>
<td>#Html.DisplayFor(modelItem => item.RouteCode)</td>
<td>#Html.DisplayFor(modelItem => item.RouteID)</td>
<td>#Html.DisplayFor(modelItem => item.SiteNumber)</td>
<td>#Html.DisplayFor(modelItem => item.SystemCode)</td>
</tr>
}
</table>
</div>
<div class="form-group">
<div style="margin-top: 50px">
<input type="submit" id="btnLost" class="btn btn-primary" value="Lost"/>
<input type="submit" class="btn btn-primary" name="OOBButton" value="OOB" />
<input type="submit" class="btn btn-primary" name="RefusedButton" value="Refused" />
</div>
</div>
}
</div>
</div>
and finally my controller
[HttpPost]
public ActionResult SelectedCustomers(CustomerInfoList
customerNumberList)
{
return View("ViewCustomerInfo");
}
also here is my javascript for the checkboxes
[HttpPost]
public ActionResult SelectedCustomers(CustomerInfoList customerNumberList)
{
return View("ViewCustomerInfo");
}
//column checkbox select all or cancel
$("input.select-all").click(function () {
var checked = this.checked;
$("input.select-item").each(function (index, item) {
item.checked = checked;
});
});
//check selected items
$("input.select-item").click(function () {
var checked = this.checked;
console.log(checked);
checkSelected();
});
//check is all selected
function checkSelected() {
var all = $("input.select-all")[0];
var total = $("input.select-item").length;
var len = $("input.select-item:checked:checked").length;
console.log("total:" + total);
console.log("len:" + len);
all.checked = len === total;
}
});

Not sure if it is the best way to handle it but I simply added the fields that I wanted into a HiddenFor helper and they were returned to my the appropriate controller. Thanks everyone for the help.
#Html.HiddenFor(m => m.additionalCustomerInfoListView[i].CustomerNumber)

Related

MVC 5 ActionResult parameter always null

I'm pretty newbie with MVC and my English is very poor. I'm now stuck with a parameter always being null in my ActionResult parameter.
Here is the controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "TimeCodeId, Code, Title, Description, IsValid, DateCreated")] TimeCodeInfo infoTimeCode, string submitButton)
{
bool result;
switch (submitButton)
{
case "Update":
case "Enregistrer":
infoTimeCode.LastDateModified = DateTime.Now;
result = _mTimeCode.Update(infoTimeCode);
return RedirectToAction("List");
case "Cancel":
case "Annuler":
return RedirectToAction("List");
//break;
}
return View(infoTimeCode);
}
and this is the cshtml
#using (Html.BeginForm("Edit", "TimeCode", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(Model => Model.TimeCodeId)
<table class="w3-table w3-card">
<tr>
<td>Code:</td>
<td>
#Html.EditorFor(model => model.Code)
#Html.ValidationMessageFor(model => model.Code)
</td>
</tr>
<tr>
<td>Titre:</td>
<td>
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</td>
</tr>
<tr>
<td>Description:</td>
<td>
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</td>
</tr>
<tr>
<td>Est valide ?</td>
<td>
#Html.EditorFor(model => model.IsValid)
#Html.ValidationMessageFor(model => model.IsValid)
<label class="switch" onsubmit="#Model.IsValid = getCheckBoxValue('switchCheckBox')">
<input id="switchCheckBox" type="checkbox" name="IsValid">
<span class="slider round"></span>
</label>
</td>
</tr>
<tr>
<td>Date de création:</td>
<td>#Model.DateCreated</td>
</tr>
<tr>
<td>Dernière modification:</td>
<td>#Model.LastDateModified</td>
</tr>
</table>
<br />
<i class="fa fa-caret-left"></i> Retour à la liste
<div class="float-right">
<button type="submit" value="enregistrer"> enregistrer </button>
#*<a type="submit" href="~/Views/TimeCode/List.cshtml" class="w3-right w3-round-medium button buttonBlue">Enregistrer</a>*#
Annuler
</div>
}
Parameter submitButton is always null when I debug it. Is someone seeing where the problem is? Do I have to add more details?
Thank you!

ASP.NET MVC 5 HttpPostedFileBase always null

I checked everything and can't figure it out. The Form is multipart/form-data, the name of the input matches the name of the variable in the post method, and still the file is always null and Request.Files is always empty.
#model Gnosis.View.Areas.OpportunityAction.Models.Rfp.RfpModel
#using (Html.BeginForm(MVC.OpportunityAction.ChangeRfp.Edit(), FormMethod.Post, new { enctype = "multipart/form-data", id="submitForm" }))
{
<input type="file" name="file" id="file" style="width: 400px"/>
}
controller method
[HttpPost]
public virtual ActionResult Edit(HttpPostedFileBase file, RfpModel model)
{
}
If I do an ajax post that works, but I should work with MVC mechanisms also and can't figure it out why it doesn't...
Update. This is the code in the view:
#model Gnosis.View.Areas.OpportunityAction.Models.Rfp.RfpModel
#using (Html.BeginForm(MVC.OpportunityAction.ChangeRfp.Edit(), FormMethod.Post, new { enctype = "multipart/form-data", id="submitForm" }))
{
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.SystemEditDate)
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Attachment)
#Html.HiddenFor(m => m.Description)
#Html.HiddenFor(m => m.FileSize)
#Html.HiddenFor(m => m.FileDate)
#Html.HiddenFor(m => m.FileTime)
#Html.HiddenFor(m => m.FileExtension)
#Html.HiddenFor(m => m.OpportunityRfpId)
<table class="keyvalue withrowpadding">
<tr>
<td class="key">#Html.LabelFor(m => m.Rfp)</td>
<td class="value">#Html.EditorFor(m => m.Rfp)</td>
</tr>
<tr>
<td class="key">#Html.LabelFor(m => m.RfpDate)</td>
<td class="value">#Html.EditorFor(m => m.RfpDate)</td>
</tr>
<tr>
<td class="key">#Html.LabelFor(m => m.FileName)</td>
<td class="value">#Html.TextBox("NameForDisplay", Model.FileName, new {disabled = "disabled", style = "width:300px"})</td>
</tr>
<tr>
<td class="key">RFP File Name:</td>
<td class="value"><input type="file" name="file" id="file" style="width: 400px"/> #Html.ValidationMessageFor(m => m.Attachment)</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="Save" id="Save"/>
<input type="button" value="Cancel"/>
</td>
</tr>
</table>
#Html.ValidationSummary()
}
<script>
$(document).on('click', '#Save', function () {
var vcfData = new FormData($('#submitForm')[0]);
var rfp = $("#Rfp").val();
var rfpDate = $("#RfpDate").val();
var id = $("#Id").val();
var opportunityRfpId = $("#OpportunityRfpId").val();
console.log(id);
$.ajax({
url: '#Url.Action(MVC.OpportunityAction.ChangeRfp.SubmitFile())' + "?file=" + vcfData + '&id=' + id + '&Rfp=' + rfp + '&RfpDate=' + rfpDate + '&OpportunityRfpId='+ opportunityRfpId,
type: "post",
data: vcfData,
processData: false,
contentType: false,
cache: false,
success: function (data) {
}
});
});
</script>
The code is inherited, and probably the original developer couldn't figure out this puzzle either so he did the ajax post. But I need to expand this functionality, and it needs to be done in the Edit method and dependent on processing of this file...

#Html.HiddenFor returning null value

I am trying to return the results of a table back to the controller for further manipulation. Once returned to the controller the value shows as null. In the past I have been able to use #Html.HiddenFor to return the values but it doesn't seem to be working in this instance. Not sure what I am doing wrong here. Any help is greatly appreciated.
#model IEnumerable<Project.Models.Item>
#{
ViewBag.Title = "Welcome to The Project";
}
#using (Html.BeginForm("UpdateQuality", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="row">
<div class="form-group">
<table class="table table-bordered">
<tr>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.SellIn)</th>
<th>#Html.DisplayNameFor(m => m.Quality)</th>
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(m => m.ElementAt(i).Name)</td>
<td>#Html.DisplayFor(m => m.ElementAt(i).SellIn)</td>
<td>#Html.DisplayFor(m => m.ElementAt(i).Quality)</td>
#Html.HiddenFor(m => m.ElementAt(i).Name)
#Html.HiddenFor(m => m.ElementAt(i).SellIn)
#Html.HiddenFor(m => m.ElementAt(i).Quality)
</tr>
}
</table>
<div class="form-group">
<div style="margin-top: 50px">
<input type="submit" class="btn btn-primary" value="Advance Day"/>
</div>
</div>
</div>
</div>
}
And here is the controller which returns null.
public ActionResult UpdateQuality(List<Item> Items )
{
return View("Index", (object)Items);
}
You cannot use ElementAt() in a HtmlHelper method that generates form controls (look at the name attribute your generating - it does not match your model).
Either change the model to be IList<T>
#model List<Project.Models.Item>
and use a for loop
#for (int i = 0; i < Model.Count; i++)
{
....
#Html.HiddenFor(m => m.[i].Name)
....
or change use a custom EditorTemplate for typeof Item, and in the main view, use #Html.EditorFor(m => m) to generate the correct html for each item in the collection.

error when update data to database using checkbox

i try to update my database using checkbox, when i delete data, my code is work. but when i update to add some value to database, i got some error.
**
Cannot insert explicit value for identity column in table 'HotelRoomFacility' when IDENTITY_INSERT is set to OFF.
**
this my code
my service
public void UpdateFacilityInHotel(List<int> FacilityIDs, int RoomTypeID)
{
List<HotelRoomFacility> hotelRoomFacilities = _HotelRoomFacility.AsQueryable().Where(f => f.RoomTypeID == RoomTypeID).ToList();
foreach (int newFacility in FacilityIDs)
{
if (hotelRoomFacilities.Where(h => h.RoomFacilityID == newFacility).Count() == 0)
{
HotelRoomFacility facility = new HotelRoomFacility
{
RoomFacilityID = newFacility,
RoomTypeID = RoomTypeID
};
_HotelRoomFacility.Add(facility);
}
}
foreach (HotelRoomFacility facility in hotelRoomFacilities)
{
if (FacilityIDs.Contains(facility.RoomFacilityID) == false)
_HotelRoomFacility.Delete(facility);
}
_HotelFacilityRepository.CommitChanges();
}
my controller
public ActionResult EditRoom(int RoomTypeID)
{
ViewBag.hotel = _hotelService.GetByID(_HotelID).HotelName;
//var roomType = _hotelService.ShowRoomByID(RoomTypeID);
//return View(roomType);
List<EditRoomTypeViewModel> editRoomTypeViewModel = _showRoomByIDService.ShowRoomByID(RoomTypeID);
return View(editRoomTypeViewModel.FirstOrDefault());
}
[HttpPost]
public ActionResult EditRoom(EditRoomTypeViewModel typeRoom, FormCollection forms)
{
List<string> IDs = forms["FacilityIDs"].Split(',').ToList();
List<int> FacilityIDs = new List<int>();
foreach (string ID in IDs)
{
FacilityIDs.Add(Convert.ToInt32(ID));
}
_showRoomByIDService.UpdateFacilityInHotel(FacilityIDs, _HotelID);
return EditRoom(_HotelID);
var x = _hotelService.UpdateRoom(typeRoom.RoomTypeID, typeRoom.RoomTypeName, typeRoom.RoomTypeDescription);
if (x != null)
{
return RedirectToAction("Room");
}
return View(typeRoom);
}
my view
#model XNet.Repository.Model.EditRoomTypeViewModel
#{
ViewBag.Title = "addRoom";
}
<h2>Edit Room</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Isikan Data</legend>
<div>
#Html.Label("Hotel Name")
</div>
<div>
#ViewBag.hotel
</div>
<br />
<div>
#Html.HiddenFor(model => model.RoomTypeID)
</div>
<br />
<div>
#Html.Label("Room Type Name")
</div>
<div>
#Html.EditorFor(model => model.RoomTypeName)
#Html.ValidationMessageFor(model => model.RoomTypeName)
</div>
<br />
<div>
#Html.Label("Room Type Description")
</div>
<div>
#Html.TextAreaFor(model => model.RoomTypeDescription)
#Html.ValidationMessageFor(model => model.RoomTypeDescription)
</div>
<br />
<table>
<thead>
<tr>
<th>Facility Name</th>
<th> is available</th>
</tr>
</thead>
<tbody>
#foreach (var facility in Model.facilitiesInRoom)
{
<tr>
<td>
#(facility.RoomFacilityName)
</td>
<td style="text-align:center;">
<input type="checkbox" #(facility.RoomFacilityAvailable ? " checked=checked" : null) name="FacilityIDs" value="#facility.RoomFacilityID" />
</td>
</tr>
}
</tbody>
</table>
<br />
<p>
<input type="submit" value="Save" />
<input style="width:100px;" type="button" title="EditHotelDetail" value="Back to Detail" onclick="location.href='#Url.Action("Index", "Hotel") '" />
</p>
</fieldset>
}
Here is the database diagram

Why the value is changed after clicking the submit button?

I make one action method for 2 activities (new input and edit), and there is also only one
view to handle those activities.
But I don't understand no matter what activity happen, the action method always think it is a new input.
I learned that it because of the ID is always 0, but the problem is, when doing the edit, when in the view the ID is correct as the ID of the data, but when I click the submit button, the action method just see the 0 value of ID.
Here is the action method I used:
[HttpPost]
public ActionResult AddAssignment(SateliteSchedule SatSched)
{
var txt = "";
if (ModelState.IsValid)
{
if (SatSched.ID == 0)
{
db.SateliteSchedules.Add(SatSched);
txt = "{0} has been added!";
}
else
{
db.Entry(SatSched).State = EntityState.Modified;
txt = "{0} has been modified!";
}
db.SaveChanges();
Utility utl = new Utility();
TempData["message"] = string.Format(txt, utl.GetSateliteName(SatSched.SateliteID));
return RedirectToAction("FormAssignment");
}
else
{
ViewBag.Message = "ModelState is not Valid!";
return View("ErrorView");
}
}
And here is the view:
#using (Html.BeginForm("AddAssignment", "admin", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td>#Html.LabelFor(m => m.Tanggal)
</td>
<td>
#Html.EditorFor(m => m.Tanggal)
#Html.ValidationMessageFor(m => m.Tanggal)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SateliteID)</td>
<td>
#Html.DropDownList("SateliteID", (IEnumerable<SelectListItem>)ViewBag.SatList, "--- Satelite ---")
#Html.ValidationMessageFor(m => m.SateliteID)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.WMOnDuty)</td>
<td>
#Html.DropDownList("WMOnDuty", (IEnumerable<SelectListItem>)ViewBag.WMList, "--- Worship Manager ---")
#Html.ValidationMessageFor(m => m.WMOnDuty)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SMOnDuty)</td>
<td>#Html.EditorFor(m => m.SMOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.WLOnDuty)</td>
<td>#Html.EditorFor(m => m.WLOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.MLOnDuty)</td>
<td>#Html.EditorFor(m => m.MLOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SoundMan)</td>
<td>#Html.EditorFor(m => m.SoundMan)</td>
</tr>
<tr>
<td valign=top>#Html.LabelFor(m => m.Note)</td>
<td>#Html.TextAreaFor(model => model.Note, new { #class = "memo-text" })</td>
</tr>
</table>
<div>
<input type="submit" value="Save" />
#Html.ActionLink("Kembali", "FormAssignment")
</div>
}
What should I check to fix this?
You have to have the Id as a hidden, so when you go in the method the model will have the id asigned to it (does it make sense?). try placing this in your form
#Html.HiddenFor(m => m.ID)

Resources