Functionality: when I select the drop-down list box, the current values are shown in a message box, asking you if you want to copy the row info of 5 cells in the columns to the empty row in green. If you choose "Yes", then it will copy them to that row then clear what it copied in the current row there after. If you choose "No", then it will cancel, the box will become unchecked and drop-down box will hide once again.
I cannot figure out how to copy the info to the green row designated by the id from the drop-down box?
Any help would be greatly appreciated!
WebGrid:
[Code]
#model YardDog.Model.YardDogModel
#{
Layout = null;
ViewBag.Title = "Yard Dog";
WebGrid webGrid = new WebGrid(source: Model.LocationData, canPage: true, canSort: true,
sortDirectionFieldName: "Section", rowsPerPage: 50);
webGrid.Pager(WebGridPagerModes.All);
}
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="#Url.Content("~/Content/YardDogStyle.css")" rel="stylesheet" type="text/css"
/>
<link href="#Url.Content("~/Scripts/jquery-3.4.1.min.js")" rel="stylesheet"
type="text/css" />
<link href="#Url.Content("~/Scripts/bootstrap.min.js")" rel="stylesheet" type="text/css"
/>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
</head>
<body>
<div class="DivDropDown">
#{ int firstRecord = (webGrid.PageIndex * webGrid.RowsPerPage) + 1;
int lastRecord = (webGrid.PageIndex * webGrid.RowsPerPage) +
webGrid.Rows.Count();
}
<div id="RowCountTop"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
<br />
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #Id =
"formYardDog" }))
{
//Loop to Get Dictionary List Buttons with Distinct Section Values.
for (int i = 0; i < Model.Section.Count; i++)
{
<input type="submit" name="#Html.NameFor(model => model.Section)"
value=#Model.Section[i].Value id="ddlSectionButtons" , new {
onclick="document.forms[0].submit();" class="ddlSectionButtons" onClick="focusMe(this);"
} />
}
<!-- All Sections Button for PlantLocation -->
<button text="All" value=" " type="submit" name="#Html.NameFor(model =>
model.Section)" , new { onclick="document.forms[0].submit();" onClick="focusMe(this);"
id="ddlSectionAllButton" class="ddlSectionButtons" placeholder="All" hidden="hidden"
})>All</button>
<!-- No need for Second Section Drop-Down Box -->
//Html.LabelFor(model => model.Section, "All", new { onchange =
"document.forms[0].submit();", id = "ddlSectionAllButtonLbl", Class
="ddlSectionButtons", placeholder = "All" })
}
<img id="OpenPanelButton" class="OpenPanelButton"
src="~/images/OpenPanelButton.PNG" href="" />
<!-- Begin Collaspable Panel with Div -->
<div id="panel">
<br />
#Html.DropDownListFor(model => model.Section, Model.Section, "Section",
new { onchange = "document.forms[0].submit();", #id = "ddlSection", #class =
"ddlSection" })
#Html.DropDownListFor(model => model.PlantLocation, Model.PlantLocation,
"PlantLocation", new { onchange = "document.forms[0].submit();", #id = "ddlWarehouses",
#class = "ddlWarehouses" })
<br /><br />
<label id="AddNewRow_Lbl" class="AddNewRow_Lbl">Add New Row: </label>
#Html.TextBoxFor(model => model.Input_Location, new { id =
"Input_Location", Class = "NewRow", placeholder = "Location" })
#Html.TextBoxFor(model => model.Input_Section, new { id =
"Input_Section", Class = "NewRow", placeholder = "Section" })
#Html.TextBoxFor(model => model.Input_TrailerNumber, new { id =
"Input_TrailerNumber", Class = "NewRow", placeholder = "TrailerNumber" })
#Html.TextBoxFor(model => model.Input_CarrierName, new { id =
"Input_CarrierName", Class = "NewRow", placeholder = "CarrierName" })
#Html.TextBoxFor(model => model.Input_CommodityLoadStatus, new { id =
"Input_CommodityLoadStatus", Class = "NewRow", placeholder = "CommodityLoadStatus" })
#Html.TextBoxFor(model => model.Input_PlantLocation, new { id =
"Input_PlantLocation", Class = "NewRow", placeholder = "PlantLocation" })
<button id="NewRowSubmitButton" type="submit"
OnClick="NewRowSubmitButton_Click()">Submit</button>
</div>
<hr />
<div id="content">
#webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { #id = "webGrid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:#<span class="link">
<!--Add Checkbox here-->
#Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new
{ #Class = "SelectedMoveIsChecked", #id = "SelectedMoveIsChecked", #checked = false })
#Html.CheckBoxFor(model => model.SelectedMoveToChecked, new
{ #Class = "SelectedMoveToChecked", #id = "SelectedMoveToChecked", #checked = false })
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;"
style="display:none">Update</a>
<a class="Cancel" href="javascript:;"
style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "LocationID", format: #<span
class="label">#item.LocationID</span>, style: "LocationID"),
webGrid.Column(header: "Location", format: #<span>
#Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended,
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", #id =
"RowLocationDropDownList", #class = "RowLocationDropDownList", #visibility = "hidden",
#placeholder = "Location" })<br />
<span class="label">#item.Location</span>
</span>, style: "Location"),
webGrid.Column(header: "Section", format: #<span
class="label">#item.Section</span>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: #<span>
<span class="label">#item.TrailerNumber</span>
<input id="TrailerNumber" class="text" type="text"
value="#item.TrailerNumber" style="display:none" />
</span>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: #<span>
<span class="label">#item.CarrierName</span>
<input id="CarrierName" class="text" type="text"
value="#item.CarrierName" style="display:none" />
</span>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: #<span>
<span class="label">#item.LoadCommodityStatus</span>
<input id="LoadCommodityStatus" class="text" type="text"
value="#item.LoadCommodityStatus" style="display:none" />
</span>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format: #<span
class="label">#item.DateLoaded</span>, style: "DateLoaded"),
webGrid.Column(header: "PlantLocation", format: #<span>
<span class="label">#item.PlantLocation</span>
</span>, style: "PlantLocation"))),
<div id="RowCountBpttom"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
</div>
<br /><br />
<div class="WebGridTable">
</div>
</div>
</form>
</div>
<script>
//================== Checkbox Selection/Control =====================
//$('#panel').accordion.hide();
$("#panel").fadeToggle('777');
$('#OpenPanelButton').click(function () {
$("#panel").fadeToggle('777');
});
//Paint the rows Green that are TrailerNumber (Empty) and hide the checkboxes.
$("#content tbody tr").each(function (i, row) {
var $CheckBoxRowNull = $(row);
if ($('#ddlWarehouses').val() == '') {
$('.SelectedMoveIsChecked').attr('disabled', true);
}
if ($CheckBoxRowNull.find('#TrailerNumber').val() == '') {
$CheckBoxRowNull.css('background-color',
'#AFE1AF').find('.SelectedMoveIsChecked').hide();
};
//Places Row List Boxes for ListLocation, ListSection, and SelectMoveCheckBox.
var $CheckBoxRowChecked = $(row);
if ($CheckBoxRowChecked.find('#TrailerNumber').val() != '') {
$CheckBoxRowChecked.find('.RowLocationDropDownList').fadeIn('777').show(),
$CheckBoxRowChecked.find('.RowSectionDropDownList').fadeIn('777').show();
$CheckBoxRowChecked.find('.SelectedMoveIsChecked').fadeIn('777').show();
};
//========================= Inner Query =============================
//When the checkbox is checked enable the dropdownlistbox and loop through to
disable dropdownlist box when not checked.
$(".SelectedMoveIsChecked").change(function () {
$('.SelectedMoveIsChecked').each(function () {
if ($(this).prop('checked')) {
$(this).closest('tr').find('select.RowLocationDropDownList').removeAttr('disabled');
} else {
$(this).closest('tr').find('select.RowLocationDropDownList').attr('disabled', true);
}
});
});
//Check the box and the row turns red that is checked.
$('.SelectedMoveIsChecked').click(function (i, row) {
var $actualRow = $(row);
var backgroundColorRedRow = $(this).is(":checked") ? "#EE4B2B;" : "5"; //Red
Color.
var RowLocationDropDownList = $(this).is(":checked") ? "disabled" : false;
$(this).closest('tr').attr('style', 'background-color: ' +
backgroundColorRedRow + ';')
//Allow only one selection of the row to be checked.
$(".SelectedMoveIsChecked").not(this).prop('checked', false);
$(".SelectedMoveToChecked").not(this).prop('checked', false); //Green can be
checked when checkbox shown there (always hidden).
if ($actualRow.find('#TrailerNumber').val() != '') {
$actualRow.find('.RowLocationDropDownList').show(),
$actualRow.find('.RowSectionDropDownList').show();
}
//Show the Row DropDownList Box in the row that doesn't have a trailer
number.
$('#content tbody tr').find('#TrailerNumber' != '')(function (i, row) {
var $actualRow = $(row);
$actualRow.find('.RowLocationDropDownList').fadeIn(777).fadeToggle().show(),
$actualRow.find('.RowSectionDropDownList').fadeIn(777).fadeToggle().show();
}).change();
//================ Change Background Color upon Selection ==============
//Turns all rows Green that have empty TrailerNumber values and hides all
the checkboxes in the green rows.
$("#content tbody tr").each(function (i, row) {
var $actualRowGreen = $(row);
if ($actualRowGreen.find('#TrailerNumber').val() == '') {
$actualRowGreen.css('background-color',
'#AFE1AF').find('.SelectedMoveIsChecked').hide(); //Green Color.
};
});
});
//Change the background colors using checkbox based on conditions.
$('#content tbody tr').each(function (i, row) {
$('input[type=checkbox]').click(function () {
$(this).closest('tr')
.attr('enabled', this.not.checked);
//Added for when the checkbox is checked.
var tdIndex = $(this).closest('td').index();
$('#WebGrid').find("tr (" + tdIndex + ")")
.attr('enabled', this.checked);
});
});
});
//Allows web grid to freeze headers.
function dataBound(args) {
this.element.find(".e-headercontent").removeClass("e-headercontent");
}
//Control the All Button to be seen when not empty.
if ($('#ddlWarehouses').val() != '') {
$('#ddlSectionAllButton').show();
};
*/
//Get selected output to alert.
//Enable the checkbox when dropdownlist is not empty, then allow selection of
checkbox too be checked.
$('select.RowLocationDropDownList').attr('disabled', true);
$(".SelectedMoveIsChecked").change(function (i, row) {
var $actualRow = $(row);
$actualRowColorRed = $(row);
//Only allow one DropDownRowList Box to be enabled when checkbox is checked.
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
var $actualRow = $(row);
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing
data and color the row red again.
if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[0];
var RowSection = ret[1];
var RowLocation = ret[2];
var ConfirmStr = "Are you sure, you want to move this row to\n
Section: ";
alert("Original: " + str + " " + ConfirmStr + " RowPageID: " +
RowLocationID + " Section: " + RowSection + " Location: " + RowLocation + "?");
var $actualRow = $(row);
var backgroundColorRedRow = $(this).is(":checked") ? "#EE4B2B;" :
""; //Red Color.
$actualRow(this).closest('tr').attr('style', 'background-color: ' +
backgroundColorRedRow)
}
});
}
});
//DropDownList Warehouse handler.
$("body").on("change", "#ddlWarehouses", function () {
$('#formYardDog')[0].submit();
});
$("body").on("click", "#webGrid tfoot a", function () {
$('#formYardDog').attr('action', $(this).attr('href')).submit();
return false;
});
//DropDownList Section handler.
$("body").on("change", ".ddlSection", function () {
$('#formYardDog')[0].submit();
});
$("body").on("click", "#webGrid tfoot a", function () {
$('#formYardDog').attr('action', $(this).attr('href')).submit();
return false;
});
//List Section Buttons handler.
$("body").on("click", ".ddlSectionButtons", function () {
$('#formYardDog')[0].submit();
});
$("body").on("click", "#webGrid tfoot a", function () {
$('#formYardDog').attr('action', $(this).attr('href')).submit();
return false;
});
//Edit event handler.
$("body").on("click", "#webGrid TBODY .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
$(this).find(".text").show();
$(this).find(".label").hide();
}
});
row.find(".Clear").hide();
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
//Clear event handler.
$("body").on("click", "#webGrid TBODY .Clear", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus =
row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
//Update event handler.
$("body").on("click", "#webGrid TBODY .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
row.find(".Clear").show();
$(this).hide();
var customer = {};
customer.LocationID = row.find(".LocationID").find(".label").html();
customer.UserName = row.find(".UserName").find(".label").html();
customer.Location = row.find(".Location").find(".label").html();
customer.Section = row.find(".Section").find(".label").html();
customer.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
customer.CarrierName = row.find(".CarrierName").find(".label").html();
customer.LoadCommodityStatus =
row.find(".LoadCommodityStatus").find(".label").html();
customer.DateLoaded = row.find(".DateLoaded").find(".label").html();
customer.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 777);
});
//Cancel event handler.
$("body").on("click", "#webGrid TBODY .Cancel", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
input.val(span.html());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Clear").show();
row.find(".Update").hide();
$(this).hide();
setInterval('location.reload()', 777);
});
</script>
</body>
[/Code]
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
YardDogModel model = PopulateModel(null, null);
return View(model);
}
// Controls DropDownList PlantLocation/Section Selection.
[HttpPost]
public ActionResult Index(string plantLocation, string section)
{
YardDogModel model = PopulateModel(plantLocation, section);
return View(model);
}
// Population Controller.
public static YardDogModel PopulateModel(string country, string city)
{
using (PW_YardDogDataEntitiesModel3 entities = new
PW_YardDogDataEntitiesModel3())
{
YardDogModel model = new YardDogModel()
{
LocationDatas = (from c in entities.LocationDatas
where c.PlantLocation == country && c.Section == city
&& c.Section == c.Section && c.Location == c.Location && c.PlantLocation == country ||
string.IsNullOrEmpty(country) || string.IsNullOrEmpty(city) && c.PlantLocation ==
country
select c).ToList(),
LocationList = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Location) && c.Location !=
null && !string.IsNullOrEmpty(c.Section) && country == c.PlantLocation // && country
==
c.PlantLocation// && townList == c.Location // && city == c.Section && country ==
c.PlantLocation
select new SelectListItem { Text = c.Location, Value =
c.Location }).Distinct().ToList(),
SectionList = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Section) && c.Section !=
null && country == c.PlantLocation
select new SelectListItem { Text = c.Section, Value =
c.Section }).Distinct().ToList(),
Section = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Section) && c.Section != null
&& country == c.PlantLocation
select new SelectListItem { Text = c.Section, Value =
c.Section }).Distinct().ToList(),
PlantLocation = (from c in entities.LocationDatas
where (c.PlantLocation == c.PlantLocation)
select new SelectListItem { Text = c.PlantLocation,
Value = c.PlantLocation }).Distinct().ToList(),
LocationAppended = (from c in entities.LocationDatas
where !string.IsNullOrEmpty(c.Section) && c.Section
!= null && country == c.PlantLocation && string.IsNullOrEmpty(c.TrailerNumber)
select new SelectListItem { Text = c.LocationID + "
" + c.Section + " " + c.Location, Value = c.LocationID + " " + c.Section + " " +
c.Location
}).Distinct().ToList(),
//LocationAppendedLbl = LocationAppended,
};
return model;
}
}
[HttpPost]
public ActionResult UpdateCustomer(LocationData customer)
{
using (PW_YardDogDataEntitiesModel3 entities = new
PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == customer.LocationID
select c).FirstOrDefault();
if (customer.TrailerNumber != null) updatedCustomer.TrailerNumber =
customer.TrailerNumber.ToUpper();
else updatedCustomer.TrailerNumber = customer.TrailerNumber = null;
if (customer.CarrierName != null) updatedCustomer.CarrierName =
customer.CarrierName.ToUpper();
else updatedCustomer.CarrierName = customer.CarrierName = null;
if (customer.LoadCommodityStatus != null)
updatedCustomer.LoadCommodityStatus = customer.LoadCommodityStatus.ToUpper();
else updatedCustomer.LoadCommodityStatus = customer.LoadCommodityStatus =
null;
//Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
customer.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = customer.DateLoaded;
entities.SaveChanges();
//Refresh(out, customer.ToString());
}
return new EmptyResult();
}
// Refresh the Form on Data changes.
// Clear the three columns in the Web Grid.
[HttpPost]
public ActionResult ClearCustomer(LocationData clear)
{
using (PW_YardDogDataEntitiesModel3 entities = new
PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == clear.LocationID
select c).FirstOrDefault();
if (clear.TrailerNumber != null) updatedCustomer.TrailerNumber = null;
else updatedCustomer.TrailerNumber = clear.TrailerNumber = null;
if (clear.CarrierName != null) updatedCustomer.CarrierName = null;
else updatedCustomer.CarrierName = clear.CarrierName = null;
if (clear.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus =
null;
else updatedCustomer.LoadCommodityStatus = clear.LoadCommodityStatus = null;
entities.SaveChanges();
}
return new EmptyResult();
}
}
Model:
public class YardDogModel
{
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
public List<SelectListItem> LocationAppended { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
public bool SelectedMoveIsChecked { get; set; } = false;
public bool SelectedMoveToChecked { get; set; } = false;
public string LocationAppendedLbl { get; internal set; }
}
Figured it out, including clearing the initial row after the data is moved:
$('select.RowLocationDropDownList').hide();
$(".SelectedMoveIsChecked").change(function (i, row) {
$actualRowColorRed = $(row);
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
/////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[2];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[0];
var RowLocation = ret[1];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
$("body").on("change", "select.RowLocationDropDownList", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
var ToRow = {};
ToRow.LocationID = RowLocationIDNum;
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/YardDogAdmin/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/YardDogAdmin/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 500);
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
});
}
});
I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable
I've got a very basic MVC project that does maths operations (+ - / *) of 2 numbers
for some reasons my view is not updating after postback
here is my controller
namespace MathsAppMVC.Controllers
{
public class HomeController : Controller
{
MathsServiceClient loClient = new MathsServiceClient();
Int32 loNum1 = 0;
Int32 loNum2 = 0;
//Int32 result = 0;
String locOperation = "Add";
public ActionResult Index()
{
var model = new MathsModel
{
Number1 = loNum1,
Number2 = loNum2,
//Result = result,
MathsOperation = locOperation
};
return View(model);
}
[HttpGet]
public ActionResult MathsOperation()
{
return View();
}
[HttpPost]
public ActionResult MathsOperation(MathsModel mathsModel)
{
loNum1 = mathsModel.Number1;
loNum2 = mathsModel.Number2;
locOperation = mathsModel.MathsOperation;
if (locOperation == "Add")
{
mathsModel.Result = loClient.add(loNum1, loNum2);
}
else if (locOperation == "Subtract")
{
mathsModel.Result = loClient.subtract(loNum1, loNum2);
}
else if (locOperation == "Multiple")
{
mathsModel.Result = loClient.multiple(loNum1, loNum2);
}
else
if (locOperation == "Divide")
{
mathsModel.Result = loClient.divide(loNum1, loNum2);
}
if (ModelState.IsValid)
{
return View("Index", mathsModel);
}
else
{
return View("Index");
}
}
}
}
HERE IS VIEW
#model MathsAppMVC.Models.MathsModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("MathsOperation", "Home", FormMethod.Post, new { }))
{
<fieldset>
<legend>Maths:</legend>
<div>#Html.LabelFor(u=>u.MathsOperation)</div>
<div>#Html.DropDownListFor(u => u.MathsOperation, new SelectList(
new List<Object>
{
new { value = "Add" , text = "Add" },
new { value = "Subtract" , text = "Subtract" },
new { value = "Multiple" , text = "Multiple"},
new { value = "Divide" , text = "Divide"}
},
"value",
"text",
0))
</div>
<div>#Html.LabelFor(u=>u.Number1)</div>
<div>#Html.TextBoxFor(u=>u.Number1)</div>
<div>#Html.LabelFor(u=>u.Number2)</div>
<div>#Html.TextBoxFor(u=>u.Number2)</div>
<div>#Html.LabelFor(u=>u.Result)</div>
<div>#Html.DisplayTextFor(u=>u.Result)</div>
<input type="submit" value ="Calculate" />
<input type="reset" value ="Clear" />
</fieldset>
}
In the view after postback for what ever reason the Result is always 0.
Some one please help?
I hate to post this as an answer, but that's all I can do with my amount of reputation. I literally copied and pasted your code into a new MVC project and it works fine. Can you post your MathsServiceClient code?
I am trying to build a website that is hosted on Azure as a free website, it is using MVC4, with KnockoutMVC. The website is updating a table every 4 seconds from the controller. The code executes without problem locally, however when I deploy it to the Azure website, it does not process updates.
I now have started a completely new MVC 4 project, with some simple functions using knockout, showing the current time, and updating this every .5 of a second from the controller, it is using the same structure as the javascript I have written for the proper website. It is giving the same problem, and it appears as if the ko.ServerAction call is halting the javascript function.
View
#using PerpetuumSoft.Knockout
#model MVCHelloWorld.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
#ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time"></div>
<label>Knockout time</label>
#ko.Html.Span(m => m.Time)
</body>
#ko.Apply(Model)
Controller
namespace MVCHelloWorld.Controllers
{
public class HelloWorldController : BaseController
{
public HelloWorldModel model = new HelloWorldModel();
public ActionResult Index()
{
GetTimeDoCalculation();
return View();
}
public void GetTimeDoCalculation()
{
model.Time = DateTime.Now.ToString("H:mm:ss");
}
}
}
Model
namespace MVCHelloWorld.Models
{
public class HelloWorldModel
{
public string Time { get; set; }
}
}
Try adding this to the body of your view:
<script type="text/javascript">
#* Replace 4000 with the timeout, in milliseconds *#
window.setInterval(startTime, 4000)
</script>
Your entire view will look like this:
#using PerpetuumSoft.Knockout
#model MvcApplication2.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
#ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time">
<script type="text/javascript">
#* Replace 4000 with the timeout, in milliseconds *#
window.setInterval(startTime, 4000)
</script>
<label>Knockout time</label>
#ko.Html.Span(m => m.Time)
</div>
</body>
#ko.Apply(Model)
script
$(document).ready(function () {
$("#musteri_sno").change(function () {
var strSayacID = "";
strSayacID = $(this)[0].value; // get the selected state id
var url = "/SayacOkumalari/MusteriSayaclariniGetir/" + strSayacID ;
// call controller's action
$.getJSON(url, null, function (data) {
// do something once the data is retrieved
$("#sayac_no").empty();
$.each(data, function (index, optionData) {
$("#sayac_no").append("<option value='"
+ optionData.sno
+ "'>" + optionData.sayac_seri_no
+ "</option>");
});
});
})
.change(); // making sure the event runs on initialization for default value
});
html
<td>
#Html.DropDownList("musteri_sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--", new { id = "musteri_sno" })
</td>
<td>
#Html.DropDownList("sayac_no", Enumerable.Empty<SelectListItem>(), "-- Sayaç Seçiniz --", new { id = "sayac_no" })
</td>
action
[HttpGet]
public ActionResult MusteriSayaclariniGetir(int musteri_sno)
{
var sites = entity.TblSayaclar.Where(x => x.musteri_id == musteri_sno).Select(x => new { sno = x.sno, sayac_seri_no = x.seri_no });
return Json(sites, JsonRequestBehavior.AllowGet);
}
When I removed parameter musteri_no from MusteriSayaclariniGetir(int musteri_sno) action, my codes work correctly. Is there a problem with url var url = "/SayacOkumalari/MusteriSayaclariniGetir/" + strStateID; or different error?
Thanks.
It's a problem of your routing. Use "id" instead of "musteri_sno" to use the default map or add one more routing map for your controller in Global.asax.cs