Related
I have an older ASP.NET Core MVC razor partial form with 2 input fields, I am trying to set the focus on the first input field on the form load, and when the user changes the value I want to then change the focus to the second input box. This is my first project working with ASP.NET Core 2.0 razor pages.
The issue is when I try to use HTML, Java, or razor code to set the focus, it does not work. I am hoping someone can see where I am going wrong. Thank you in advance.
Update Full script
<script>
$(document).ready(function () {
$('#ordersrefresh').on("click", function (e) {
window.location.reload(true);
});
$('#orderstart').on("click", function (e) {
$('#orderstartpick').empty();
$('#orderstartdrop').empty();
$('#orderstartpriority').empty();
//$('#orderstartmodal').modal({ backdrop: 'static', keyboard: false, show: true });
$.getJSON("/orders/orderlist/picks", function (picks) {
picks.forEach(function (item) {
$('#orderstartpick').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/drops", function (drops) {
drops.forEach(function (item) {
$('#orderstartdrop').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/priorities", function (priorities) {
priorities.forEach(function (item) {
$('#orderstartpriority').append('<option value="' + item + '">' + item + '</option>');
});
});
// shows the partial form
$.getJSON("/orders/orderlist/conn", function (conn) {
if (conn == "true") {
$('#orderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
$('#orderstartmodal').on('shown.bs.model',function () {
$('#orderstartpick').focus();
})
}
else {
$('#noorderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
}
});
// Set focus on the drop input after the pick input has changed - Working
$('#orderstartpick').change(function () {
$('#orderstartdrop').focus();
});
});
$('#ordermodif').on("click", function (e) {
$('#ordermodifid').empty();
$('#ordermodifpick').empty();
$('#ordermodifdrop').empty();
$('#ordermodifpriority').empty();
//$('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
$.getJSON("/orders/orderlist/picks", function (picks) {
picks.forEach(function (item) {
$('#ordermodifpick').append('<option value="' + item + '">' + item + '</option>');
});
});
("/orders/orderlist/drops", function (drops) {
drops.forEach(function (item) {
$('#ordermodifdrop').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/priorities", function (priorities) {
priorities.forEach(function (item) {
$('#ordermodifpriority').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/ids", function (ids) {
var idscount = 0;
ids.forEach(function (item) {
$('#ordermodifid').append('<option value="' + item + '">' + item + '</option>');
++idscount;
});
if (idscount > 0) {
$('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
else {
$('#noordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
});
});
$('#ordermodifmodal').on("shown.bs.modal", function (e) {
var ordermodifid = $('#orderidmodifcurrent').val();
$.getJSON("/orders/orderlist/order", { orderid: ordermodifid }, function (order) {
$('#ordermodifmodal #ordermodifpick').val(order.pick.name);
$('#ordermodifmodal #ordermodifdrop').val(order.drop.name);
$('#ordermodifmodal #ordermodifpriority').val(order.priority);
});
});
$('#ordermodifmodal #ordermodifid').change(function (e) {
var ordermodifid = $(this).find("option:selected").val();
$.getJSON("/orders/orderlist/order", { orderid: ordermodifid }, function (order) {
$('#ordermodifmodal #ordermodifpick').val(order.pick.name);
$('#ordermodifmodal #ordermodifdrop').val(order.drop.name);
$('#ordermodifmodal #ordermodifpriority').val(order.priority);
});
});
function DeleteRenderer(data, type, row) {
var StatusColumn = row.status;
if (StatusColumn.includes("Cancelling") || (StatusColumn.includes("Canceled"))) {
return "<button class='btn btn-outline-info' disable>Delete</button>";
}
else {
return "<button class='btn btn-outline-danger'd>Delete</button>";
}
}
function CancelRenderer(data, type, row) {
var StatusColumn = row.status;
if (StatusColumn.includes("Assigned") || (StatusColumn.includes("Pending"))) {
return "<button class='btn btn-outline-warning'>Cancel</button>";
}
else {
return "<button class='btn btn-outline-info' disabled>Cancel</button>";
}
}
function ModifyRenderer(data, type, row) {
var StatusColumn = row.state;
if (StatusColumn.includes("Assigned") || (StatusColumn.includes("Pending"))) {
return "<button class='btn btn-outline-info'>Modify</button>";
}
else {
return "<button class='btn btn-outline-info' disabled>Modify</button>";
}
}
function DateRenderer(data) {
return moment(data).format('DD/MM/YYYY HH:mm:ss');
}
var table = $('#orders').DataTable({
"processing": false, // for show progress bar
"serverSide": false, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"lengthMenu": [[20, 50, -1], [20, 50, "All"]],
"pagingType": "simple",
"ajax": {
"url": "/Orders/OrderList/data", // for client side /LoadDataAll
"type": "GET", // for client side "GET"
"datatype": "json"
},
"select": 'single',
"columns": [
{ "data": "created", "render": DateRenderer, "autoWidth": true },
{ "data": "wmsid", "name": "WMSID", "autoWidth": true },
{ "data": "index", "name": "OrderID", "autoWidth": true },
{ "data": "pick.name", "name": "Pick", "autoWidth": true },
{ "data": "drop.name", "name": "Drop", "autoWidth": true },
{ "data": "sequence", "name": "Sequence", "autoWidth": true },
{ "data": "status", "name": "Status", "autoWidth": true },
{ "data": "priority", "name": "Priority", "autoWidth": true },
{ "data": "null", "render": ModifyRenderer, "orderable": false },
//{ "data": "null", "render": CancelRenderer, "orderable": false },
//{ "data": "null", "render": DeleteRenderer, "orderable": false },
]
});
$('#orders tbody').on('click', 'button', function () {
var data = table.row($(this).parents('tr')).data();
var buttontext = $(this).text();
var token = $("[name=__RequestVerificationToken]").val();
$('input[name="orderidcurrenthidden"]').val(data.wmsid);
var ordertext = data.wmsid;
if (buttontext.toUpperCase() == 'MODIFY') {
$('#ordermodifpick').empty();
$('#ordermodifdrop').empty();
$('#ordermodifpriority').empty();
$('#orderidmodifcurrent').val($('input[name="orderidcurrenthidden"]').val());
//$('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
$.ajaxSetup({ async: false });
$.getJSON("/orders/orderlist/picks", function (picks) {
picks.forEach(function (item) {
$('#ordermodifpick').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/drops", function (drops) {
drops.forEach(function (item) {
$('#ordermodifdrop').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/priorities", function (priorities) {
priorities.forEach(function (item) {
$('#ordermodifpriority').append('<option value="' + item + '">' + item + '</option>');
});
});
//$.getJSON("/orders/orderlist/ids", function (ids) {
// var idscount = 0;
// ids.forEach(function (item) {
// $('#ordermodifid').append('<option value="' + item + '">' + item + '</option>');
// ++idscount;
// }
//});
$.getJSON("/orders/orderlist/conn", function (conn) {
if (($('#ordermodifpick option').length > 0) &&
($('#ordermodifdrop option').length > 0) &&
($('#ordermodifpriority option').length > 0) &&
(conn == "true")) {
$('#ordermodifmodal .modal-title').text('MODIFY ORDER: ' + ordertext);
$('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
else {
$('#noordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
});
$.ajaxSetup({ async: true });
}
else if (buttontext.toUpperCase() == 'CANCEL') {
$.post('/orders/orderlist?handler=ordercancel', {
orderid: data.wmsid,
__RequestVerificationToken: token,
}, function (strResult) {
if (strResult == "true") {
$('#ordercancelmodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
else {
$('#noordercancelmodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
});
}
else if (buttontext.toUpperCase() == 'DELETE') {
$.post('/orders/orderlist?handler=orderdelete', {
orderid: data.wmsid,
__RequestVerificationToken: token,
}, function (strResult) {
if (strResult == "true") {
$('#orderdeletemodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
else {
$('#noorderdeletemodal').modal({ backdrop: 'static', keyboard: false, show: true });
}
});
}
});
setInterval(function () {
table.ajax.reload(null, false); // user paging is not reset on reload
}, 5000);
$(window).on('resize', function () {
$('#orders').attr("style", "");
table.columns.adjust();
});
$("input[id$='orderstartpick']").focus();
});
</script>
script
$('#orderstart').on("click", function (e) {
$('#orderstartpick').empty();
$('#orderstartdrop').empty();
$('#orderstartpriority').empty();
//$('#orderstartmodal').modal({ backdrop: 'static', keyboard: false, show: true });
$.getJSON("/orders/orderlist/picks", function (picks) {
picks.forEach(function (item) {
$('#orderstartpick').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/drops", function (drops) {
drops.forEach(function (item) {
$('#orderstartdrop').append('<option value="' + item + '">' + item + '</option>');
});
});
$.getJSON("/orders/orderlist/priorities", function (priorities) {
priorities.forEach(function (item) {
$('#orderstartpriority').append('<option value="' + item + '">' + item + '</option>');
});
});
// shows the partial form
$.getJSON("/orders/orderlist/conn", function (conn) {
if (conn == "true") {
$('#orderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
}
else {
$('#noorderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
}
});
// set focus on the pick input on form load - Not working on load
$('#orderstartmodal').on('shown.bs.model', function () {
$('#orderstartpick').focus();
});
// Hide the submit button by class name on form load - Not working on load
$('#orderstartmodal').on('shown.bs.model', function () {
$('#submitbtn').hide();
});
// Set focus on the drop
input after the pick input has
changed - Working
$('#orderstartpick').change(function () {
$('#orderstartdrop').focus();
});
});
Partial form code in my .cshtml page
<div id="orderstartmodal" class="modal fade" tabindex="-1" role="dialog">
<form method="post" asp-page-handler="orderstart">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header" style="background-color:blanchedalmond">
<h5 class="modal-title font-italic" id="orderstartmodaltitle" value="">START ORDER</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="background-color:burlywood">
<table class="table table-sm">
<tbody>
<tr>
<td align="right" width="50%">
<div class="form-group">
<label for="orderstartpick" class="col-form-label">Pick Stn.:</label>
#*<select id="orderstartpick" name="orderpick" class="select-picker" style="width:60%"></select>*#
<input type="text" autofocus="autofocus" id="**orderstartpick**" name="orderpick" style="width:60%">
#*<script type="text/javascript">document.getElementById('orderstartpick').focus();</script>*#
#*<script>document.getElementById('orderstartpick').focus();</script>*#
#* <script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#orderstartpick').focus();
});
});
</script>*#
</div>
</td>
<td align="right" width="50%">
<div class="form-group">
<label for="orderstartdrop" class="col-form-label">Drop Stn.:</label>
#*<select id="orderstartdrop" name="orderdrop" class="select-picker" style="width:60%"></select>*#
<input runat="server" type="text" id="**orderstartdrop**" name="orderdrop" style="width:60%">
</div>
</td>
</tr>
<tr style="visibility:collapse">
<td align="right" width="50%">
<div class="form-group">
<label hidden="hidden" for="orderstartpriority" class="col-form-label">Priority:</label>
<select hidden="hidden" id="orderstartpriority" name="orderpriority" class="select-picker" style="width:60%"></select>
</div>
</td>
<td width="50%">
<div hidden="hidden" class="form-group">
</div>
</td>
</tr>
<tr>
<td align="center" valign="middle" colspan="2">
<div class="form-group">
<label for="orderstartinfo" class="col-form-label">Select/Verify Parameters And Then Click:</label>
</div>
<div class="form-group">
<button runat="server" type="submit" class="btn btn-primary">START ORDER</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer" style="background-color:blanchedalmond">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</form>
</div>
I tried HTML code for focus, Fava code, and razor code, but not of the things tried to set focus to input one.
Update:
// shows the partial form
$.getJSON("/orders/orderlist/conn", function (conn) {
if (conn == "true") {
$('#orderstartmodal').modal('show');
$('#orderstartmodal').on('shown.bs.modal', function () {
$('#orderstartpick').focus();
})
}
else {
$('#noorderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
}
});
Note: As you can see, within your code snippet I can see a if conditional while loading the modal. You should please below code sippet on load just after loading the modal:
$('#orderstartmodal').on('shown.bs.modal', function () {
$('#orderstartpick').focus();
})
I tried HTML code for focus, Java code, and razor code, but not of the
things tried to set focus to input one.
Well, in this scenario, you have to write your focus script inside your main view not in parttial page of course. You can do something like below:
Script For Input Focus:
$(document).ready(function () {
$(function () {
$('#orderstartmodal').modal('show');
});
$('#orderstartmodal').on('shown.bs.modal', function () {
$('#orderstartpick').focus();
})
$("#orderstartpick").change(function () {
$('#orderstartdrop').focus();
});
});
Note: This script need to placed below your main page where you have called your partial view. As you can see I have used change and onmouseover both would perform. However, as per your description, you need on change event then set your focus to next input box that is: $('#orderstartdrop').focus();
Output:
Note: As you haven't shared your main page details, so I have just loaded below another page.
The issue I am facing is similar to this old post cascading dropdown for dynamically added row. I am using the "BeginCollectionItemCore" NuGet package to setup a set of partial views, so I have unique Id's for my controls. The problem is, I can only get the first Partial View to respond to the dropdownlist changes. The subsequent dropdownlists won't cascade. I have tried with the scripts in the partial and in the main view but both have the same end result, only the first partial will cascade. Here is my code...
Main View HTML:
#model IEnumerable<RCRTCWA.DATA.DAL.tbl_RCRTimeCards>
#{
ViewBag.Title = "Index";
}
<h2>Time Card</h2>
#using (Html.BeginForm())
{
<div id="TimeCardLines">
#foreach (var item in Model)
{
Html.RenderPartial("_TimeCardRow", item);
}
</div>
}
#Html.ActionLink("Add more time...", "_TimeCardRow", new { ViewContext.FormContext.FormId }, new { id = "addTime"})
Main View Script:
<script>
$(document).ready(function () {
debugger;
$("#addTime").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#TimeCardLines").append(html); }
});
return false;
});
//var index = "";
$(".timecardrow").focusin(function () {
var ti = $(this).find("[name='timecardrows.index']");
var index = ti.val();
$("#timecardrows_" + index + "__HRS_EndTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
$("#timecardrows_" + index + "__HRS_StartTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
//$("#.Line_TimeCard").ajaxSuccess(function () {
// $.getJSON("/TimeCard/AddTimeCardRow/", $("#.Success").html(data).show());
//});
$("#timecardrows_" + index + "__WOTicketNo").change(function () {
var tktid = $(this).val();
$("#timecardrows_" + index + "__WOTicketRepLineNo").empty();
$.ajax({
url: "/TimeCard/GetRepairLines/",
data: { ticket: tktid },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketRepLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("Error : " + response);
}
});
GetCarNumber(tktid);
});
$("#timecardrows_" + index + "__WOTicketRepLineNo").change(function () {
var line = $("#timecardrows_" + index + "__WOTicketRepLineNo").val();
$("#timecardrows_" + index + "__WOTicketLaborLineNo").empty();
$.ajax({
url: "/TimeCard/GetLineDetails/",
data: { lineid: line },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketLaborLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("error : " + response);
}
});
return false;
}).change();
function GetCarNumber(ticket) {
$.ajax({
url: "/TimeCard/GetCarNumber/",
data: { ticket: ticket },
cache: false,
type: "POST",
success: function (data) {
$("#timecardrows_" + index + "carNo").html(data).show();
},
error: function (response) {
alert("Error : " + response);
}
});
}
});
});
</script>
Partial View HTML:
#using HtmlHelpers.BeginCollectionItem
#model RCRTCWA.DATA.DAL.tbl_RCRTimeCards
<div class="timecardrow">
#using (Html.BeginCollectionItem("timecardrows"))
{
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table>
<tr>
<th class="col-sm-1">
Ticket Number
</th>
<th class="col-sm-1">
Car Number
</th>
<th class="col-sm-1">
Repair Line / Description
</th>
<th class="col-sm-1">
Labor Line / Description
</th>
<th class="col-sm-1">
Start Time
</th>
<th class="col-sm-1">
End Time
</th>
<th class="col-sm-1">
Line Complete?
</th>
</tr>
<tr>
<td class="form-group">
<div class="col-sm-1 tickets">
#Html.DropDownListFor(model => model.WOTicketNo, (SelectList)ViewData["TicketsList"], "Select one...", new { #class = "ticketddl" } )
#Html.ValidationMessageFor(model => model.WOTicketNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 cars">
<div id="carNo"></div>
#Html.HiddenFor(model => model.CarNo)
#Html.ValidationMessageFor(model => model.CarNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 replines">
#Html.DropDownListFor(model => model.WOTicketRepLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "repairddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 laborlines">
#Html.DropDownListFor(model => model.WOTicketLaborLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "lablineddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 starttime">
#Html.EditorFor(model => model.HRS_StartTime, new { #class = "start" })
#Html.ValidationMessageFor(model => model.HRS_StartTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 endtime">
#Html.EditorFor(model => model.HRS_EndTime, new { #class = "end" })
#Html.ValidationMessageFor(model => model.HRS_EndTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 completed">
#Html.EditorFor(model => model.Completed)
#Html.ValidationMessageFor(model => model.Completed, "", new { #class = "text-danger" })
</div>
</td>
#*<td class="form-group">
<div class="col-sm-1">
<input type="submit" value="Submit Line" class="btn btn-default" />
</div>
<div id="success" class="alert-danger">
</div>
</td>*#
</tr>
</table>
</div>
}
</div>
Currently I have the script in the Main View, and have attempted to get the index part of the partial view's controls when the user interacts with the partial view. I need a better way to handle this, and need to get the cascading dropdownlist's working properly.
I would prefer to have the script in the Main View (if possible) to keep things simpler.
You do not need to bind the change event handler on dropdown using concatenated id strings, which is prone to errors (typos etc) and not easily readable/maintainable. For your cascading dropdown scenario, all you care about is updating the second select element in the same row. jQuery has some handy methods like closest and find which will make our life easier.
For making it easier for future readers, I am going to assume that your first SELECT element is to render a list of countries and has a css class "countrySelect" and second one is for the states of selected country and has the css class "statesSelect" and both are in the same table row (<tr>).
When you bind the change event, make sure you use jQuery on to do so. This will enable the binding for current and future elements in the DOM .
$("#TimeCardLines").on("change","SELECT.countrySelect",function (e) {
var _this = $(this);
var v = _this.val();
// to do :Change below url variable value as needed for your code
var urlToGetSecondDropDownData = "/Home/GetStates?countryId"+v;
$.getJSON(urlToGetSecondDropDownData,
function (res) {
var items = "";
$.each(res,
function(index, item) {
items += "<option value='" + item.Value + "'>"
+ item.Text + "</option>";
});
_this.closest("tr") // Get the same table row
.find("SELECT.statesSelect") // Find the second dropdown
.html(items); // update the content of it
});
});
Assuming you have a GetStates action method which accepts a countryId param and return the corresponding states as a list of SelectListItem ( the data needed to build the second dropdown). Something like below,
public ActionResult GetStates(int countryId)
{
var states =db.States.Where(f => f.CountryId == countryId)
.Select(f => new SelectListItem() { Value = f.Id.ToString(),
Text = f.Name})
.ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
//first dropdowlist change event
$("#countryId").change(function () {
var id = this.value;
if (id == "") {
id = "0";
}
$.get('/Home/GetStates/' + id,
function (data) {
$('#stateId').find('option').remove()
$(data).each(
function (index, item) {
$('#stateId').append('<option value="' + item.Value + '">' + item.Text + '</option>')
});
}
);
});
public ActionResult GetStates(int id)
{
List<SelectListItem> StatesList= new List<SelectListItem>();
StatesList.Add(new SelectListItem { Text = "---Select State---", Value = "0" });
var getStateCollection= (from f in _ent.States
where f.CountryId == id && f.DeletedDate == null
select new { f.Id, f.Name}).ToList();
foreach (var item in getStateCollection)
{
StatesList.Add(new SelectListItem { Text = item.Name.ToString(), Value = item.Id.ToString() });
}
return Json(StatesList, JsonRequestBehavior.AllowGet);
}
I have an existing form which relies on a category being selected, if a category does not exist for the user the company belongs too, the user must be able to create one.
I believe jQuery and JSON is the route forward, but I cannot generate a true popup above the current Bootstrap form, nor can I get the popup form to post without posting the main form.
If possible I'd like the jQuery function getCategories to open a popup form only if no data is returned, then the popup form using validation, once a record has been successfully added to the database, the popup form close and then recall the jQuery function getCategories and select the newly added record.
HomeController.cs
public JsonResult GetCategories(int companyId)
{
var categories = _repository.GetCategories(companyId);
return Json(categories, JsonRequestBehavior.AllowGet);
}
_Layout.cshtml
#using Documents
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="author" content="#ViewBag.LenderName" />
<title>#ViewBag.Title - #ViewBag.LenderName</title>
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/dataTablesCss")
#Styles.Render("~/Content/blue")
<!--[if lt IE 9]>
#Scripts.Render("~/bundles/ie8")
<![endif]-->
</head>
<body class="has-navbar-fixed-top page-index">
#Scripts.Render("~/bundles/jquery")
<!--[if lt IE 9]>
#Scripts.Render("~/bundles/jqueryvalidate")
<![endif]-->
#RenderSection("featusearch", required: false)
#RenderBody()
<footer id="footer" class="text-center">
<div class="container">
<div class="row">
<div class="col-lg-12">
<p> </p>
<p>
Copyright © 2015 - #ViewBag.CompanyName
</p>
</div>
</div>
</div>
</footer>
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/dataTables")
#Scripts.Render("~/bundles/money")
#Scripts.Render("~/bundles/tooltip")
#Scripts.Render("~/bundles/jquery-ui")
<script type="text/javascript" language="javascript">
$("#menu-close").click(function (e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").click(function (e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$(function () {
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') || location.hostname === this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
<script type="text/javascript" charset="utf-8">
$(function () {
$('.validation-summary-errors').each(function () {
$(this).addClass('alert');
$(this).addClass('alert-danger');
});
$('form').each(function () {
$(this).find('div.form-group-individual').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('has-error');
$(this).find('span.field-validation-error').removeClass('field-validation-error');
}
});
});
});
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var oTable = $('#orders').dataTable({
responsive: true,
"pagingType": "full",
"iDisplayLength": 5,
"aLengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]],
columnDefs: [{ type: 'date-euro', targets: 4 }],
"aoColumns": [
{ "visible": false },
{ "bSortable": true, "bSearchable": true },
{ "bSortable": true, "bSearchable": true },
{ "bSortable": true, "bSearchable": true },
{ "bSortable": true, "bSearchable": true },
null,
null,
null
],
"order": [[0, "desc"]]
});
$('#Form').find('select').each(function () {
$(this).tooltip({
placement: "top",
trigger: "focus"
});
});
$('#Form').find('input').each(function () {
$(this).tooltip({
placement: "top",
trigger: "focus"
});
});
$('#Form').find('button').each(function () {
$(this).tooltip({
placement: "top",
trigger: "hover",
container: "body"
});
});
});
</script>
#RenderSection("scripts", false)
</body>
</html>
$(document).ready(function () {
var companyId = parseInt($('#CompanyId').val(), 0);
function getCategories() {
$.getJSON('/Home/GetCategories', { companyId: companyId }, function (data) {
$('#Categories option').remove();
$('#Categories').append('<option value="0">Please select a Category</option>');
for (var i = 0; i < data.length; i++) {
if (data[i].Id != categoryId) {
$('#Categories').append('<option value="' + data[i].Id + '">' + data[i].CategoryName + '</option>');
} else {
$('#Categories').append('<option value="' + data[i].Id + '" selected>' + data[i].CategoryName + '</option>');
}
}
if (data.length > 0) {
// We Have Date
} else {
// No Data
// Create Dialog Popup
alert('Error getting Categories, please add a Category');
}
}).fail(function () {
debugger;
alert('Error getting Categories, please add a Category');
});
}
$('#Categories').change(function () {
var selected = $(this).find('option:selected');
categoryId = selected.val();
$('#CategoryId').val(categoryId);
});
});
Index.cshtml
#using WebApplication1
#using WebApplication1.Helpers
#model WebApplication1.Models.Order
#{
ViewBag.Title = "Test";
}
<div id="navigation" class="wrapper">
<div class="navbar navbar-fixed-top" id="top">
<div class="navbar-inner">
<div class="inner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle btn btn-navbar" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/" title="Home"><h1>Test</h1><span>#ViewBag.CompanyName</span></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-right" id="main-menu">
#Html.MenuLink("Logout", "Login", "Logout", "", "Logout")
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="highlighted">
<div class="container">
<div class="header">
<h2 class="page-title">
<span>Test</span> <small>This is a test page.</small>
</h2>
<p></p>
</div>
</div>
</div>
<div id="content">
<div class="container">
<div class="row">
<div class="col-sm-12">
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form", #Id = "Form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.CategoryId, new { #Value = #ViewBag.CategoryId, #Id = "CategoryId" })
<fieldset>
<div class="form-group">
<div class="form-group-individual">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">Title</span>
#Html.DropDownListExt("SalutationId", ViewBag.SalutationList as SelectList, "Title")
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.SalutationId)</p>
</div>
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">Forename</span>
#Html.TextBoxForExt(m => m.Forename, new Dictionary<string, object> { { "Value", #ViewBag.Forename } })
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.Forename)</p>
</div>
</div>
</div>
<div class="form-group">
<div class="form-group-individual">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">Middle Name</span>
#Html.TextBoxForExt(m => m.MiddleName, new Dictionary<string, object> { { "Value", #ViewBag.MiddleName } })
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.MiddleName)</p>
</div>
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">Surname</span>
#Html.TextBoxForExt(m => m.Surname, new Dictionary<string, object> { { "Value", #ViewBag.Surname } })
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.Surname)</p>
</div>
</div>
</div>
<div class="form-group">
<div class="form-group-individual">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">Categories</span>
<select id="Categories" name="Categories" class="form-control" data-toggle="tooltip" title="Categories">
<option></option>
</select>
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.CategoryId)</p>
</div>
<div class="col-sm-1">
<button type="submit" class="btn btn-primary" name="Submit" value="Submit" title="Click to Submit">Submit</button>
</div>
</div>
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/Scripts/form.js"></script>
form.js
$(document).ready(function () {
var companyId = parseInt($('#CompanyId').val(), 0);
var categoryId = parseInt($('#CategoryId').val(), 0);
getCategories();
function getCategories() {
$.getJSON('/Home/GetCategories', { companyId: companyId }, function (data) {
$('#Categories option').remove();
$('#Categories').append('<option value="0">Please select a Category</option>');
for (var i = 0; i < data.length; i++) {
if (data[i].Id != categoryId) {
$('#Categories').append('<option value="' + data[i].Id + '">' + data[i].Category + '</option>');
} else {
$('#Categories').append('<option value="' + data[i].Id + '" selected>' + data[i].Category + '</option>');
}
}
if (data.length > 0) {
// We Have Data
} else {
// No Data
// Create Dialog Popup
alert('Error getting Categories, please add a Category');
}
}).fail(function () {
debugger;
alert('Error getting Categories, please add a Category');
});
}
$('#Categories').change(function () {
var selected = $(this).find('option:selected');
categoryId = selected.val();
$('#CategoryId').val(categoryId);
});
});
Add.cshtml
#using WebApplication1.Helpers
#model WebApplication1.Models.Category
<div id="content">
<div class="container">
<div class="row">
<div class="col-sm-4">
#using (Html.BeginForm("Add", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form", #Id = "AddForm" }))
{
#Html.HiddenFor(m => m.CompanyId, new { #Value = #ViewBag.CompanyId, #Id = "CompanyId" })
<fieldset>
<div class="form-group">
<div class="form-group-individual">
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon">Category Name</span>
#Html.TextBoxForExt(m => m.CategoryName)
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.CategoryName)</p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-1">
<button type="submit" class="btn btn-primary" name="Add" value="Add" title="Click to Add a Category">Add</button>
</div>
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
BundleConfig.cs
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.IgnoreList.Clear();
bundles.UseCdn = true;
BundleTable.EnableOptimizations = false;
bundles.Add(new ScriptBundle("~/bundles/ie8").Include(
"~/Scripts/html5shiv.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
var jquery = new ScriptBundle("~/bundles/jquery", "~/Scripts/jquery-2.1.4.js").Include(
"~/Scripts/Compatibility/jquery-1.11.3.js");
jquery.CdnFallbackExpression = "window.jQuery";
bundles.Add(jquery);
bundles.Add(new ScriptBundle("~/bundles/jqueryvalidate").Include(
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/_extensions.js"));
bundles.Add(new ScriptBundle("~/bundles/money").Include(
"~/Scripts/jquery.price_format.2.0.js"));
bundles.Add(new ScriptBundle("~/bundles/tooltip").Include(
"~/Scripts/tooltip.js"));
bundles.Add(new ScriptBundle("~/bundles/dataTables").Include(
"~/Scripts/DataTables-1.10.9/jquery.dataTables.js",
"~/Scripts/DataTables-1.10.9/dataTables.bootstrap.js",
"~/Scripts/DataTables-1.10.9/date-euro.js"));
bundles.Add(new ScriptBundle("~/bundles/awesomeMvc").Include(
"~/Scripts/AwesomeMvc.js"));
bundles.Add(new ScriptBundle("~/bundles/jquery-ui").Include(
"~/Scripts/jquery-ui.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
bundles.Add(new StyleBundle("~/Content/blue").Include(
"~/Content/colour-blue.css"));
bundles.Add(new StyleBundle("~/Content/red").Include(
"~/Content/colour-red.css"));
bundles.Add(new StyleBundle("~/Content/dataTablesCss").Include(
"~/Content/DataTables-1.10.9/dataTables.bootstrap.css",
"~/Content/DataTables-1.10.9/Buttons-1.0.3/buttons.bootstrap.css"));
}
}
Any help would be much appreciated :-)
It sounds like you might be looking for a Modal popup. Bootstrap already has this built in. You can learn about it here: http://www.w3schools.com/bootstrap/bootstrap_modal.asp
You can also pull what to show in the modal from another view using the Html.RenderPartial(view)
Following on from Drew Rochon's suggestion, I have researched and resolved my issue.
The following code is either replacement or addition where specified.
_Add.cshtml (Replacement for Add.cshtml)
#using WebApplication1.Helpers
#model WebApplication1.Models.Category
<div class="modal fade" id="AddCategoryModal" tabindex="-1" role="dialog" aria-labelledby="Add" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h5 class="modal-title">Add Category</h5>
</div>
<div class="modal-body">
#using (Html.BeginForm(null, null, FormMethod.Post, new { #Id = "AddCategoryForm" }))
{
#Html.HiddenFor(m => m.CompanyId, new { #Id = "CompanyId" })
<fieldset>
<div class="form-group">
<div class="form-group-individual">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">Category Name</span>
#Html.TextBoxForExt(m => m.CategoryName)
</div>
<p class="help-block">#Html.ValidationMessageFor(m => m.CategoryName)</p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
var path = $("#Path").val();
var companyId = parseInt($('#CompanyId').val(), 0);
var categoryId = parseInt($('#CategoryId').val(), 0);
var abort = false;
$("#AddCategoryModal").modal('show');
$('#AddCategoryModal').off("hidden.bs.modal").on('hidden.bs.modal', modalClose);
function modalClose() {
$("#AddAdvisoryModal").remove();
$('.modal-backdrop').remove();
}
$('#AddCategoryForm').formValidation({
framework: 'bootstrap',
excluded: ':disabled',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
CategoryName: {
validators: {
notEmpty: {
message: 'Category Name is required'
}
}
}
}
}).on('success.form.fv', function (e) {
e.preventDefault();
var companyId = $("#CompanyId").val();
var categoryName = $("#CategoryName").val();
var model = {
CompanyId: companyId,
CategoryName: categoryName
};
$.ajax({
url: "/Home/_Add/",
type: "POST",
contentType: "application/json;charset=utf-8;",
dataType: "html",
data: JSON.stringify(model),
success: function (markup) {
categoryId = parseInt(markup, 0);
if (categoryId > 0) {
$('#Categories').val(categoryId);
getCategories();
alert("Category added successfully.");
modalClose();
}
},
error: function () {
alert('Ajax request not recieved!');
}
});
});
function getCategories() {
$.getJSON(path + 'GetCategories', { companyId: companyId }, function (data) {
$('#Categories option').remove();
$('#Categories').append('<option value="0">Please select a Category</option>');
$('#Categories').append('<option value="9999999">Add a Category</option>');
for (var i = 0; i < data.length; i++) {
if (data[i].Id != categoryId) {
$('#Categories').append('<option value="' + data[i].Id + '">' + data[i].CategoryName + '</option>');
} else {
$('#Categories').append('<option value="' + data[i].Id + '" selected>' + data[i].CategoryName + '</option>');
}
}
if (data.length > 0) {
if (categoryId > 0) {
$('#Categories').val(categoryId);
}
} else {
alert('Error getting Categories, please add a Category');
}
}).fail(function () {
debugger;
alert('Error getting Categories, please add a Category');
});
}
$('#AddCategoryForm').find('select').each(function () {
$(this).tooltip({
placement: "top",
trigger: "focus"
});
});
$('#AddCategoryForm').find('input').each(function () {
$(this).tooltip({
placement: "top",
trigger: "focus"
});
});
});
</script>
form.js (Replacement)
$(document).ready(function () {
var companyId = parseInt($('#CompanyId').val(), 0);
var categoryId = parseInt($('#CategoryId').val(), 0);
getCategories();
$('#Categories').change(function () {
var selected = $(this).find('option:selected');
categoryId = selected.val();
if (categoryId == 9999999) {
openModal();
}
$('#CategoryId').val(categoryId);
});
function getCategories() {
$.getJSON(path + 'GetCategories', { companyId: companyId }, function (data) {
$('#Categories option').remove();
$('#Categories').append('<option value="0">Please select a Category</option>');
$('#Categories').append('<option value="9999999">Add a Category</option>');
for (var i = 0; i < data.length; i++) {
if (data[i].Id != categoryId) {
$('#Categories').append('<option value="' + data[i].Id + '">' + data[i].CategoryName + '</option>');
} else {
$('#Categories').append('<option value="' + data[i].Id + '" selected>' + data[i].CategoryName + '</option>');
}
}
if (data.length > 0) {
if (categoryId > 0) {
$('#Categories').val(categoryId);
}
} else {
alert('Error getting Categories, please add a Category');
openModal();
}
}).fail(function () {
debugger;
alert('Error getting Categories, please add a Category');
});
}
function openModal() {
var companyId = $("#CompanyId").val();
var model = { CompanyId: companyId };
$.ajax({
url: "/Home/_Add/",
type: "POST",
contentType: "application/json;charset=utf-8;",
dataType: "html",
data: JSON.stringify(model),
success: function (markup) {
if (isNaN(markup) || markup == "0") {
$(document.body).append(markup);
}
}
});
}
});
BundleConfig.cs (Addition)
bundles.Add(new StyleBundle("~/Content/formValidationCss").Include(
"~/Content/formValidation.css"));
bundles.Add(new ScriptBundle("~/bundles/formValidation").Include(
"~/Scripts/formValidation.min.js",
"~/Scripts/foundationBootstrap.min.js",
"~/Scripts/foundation.min.js"));
_Layout.cshtml (Addition)
#Styles.Render("~/Content/formValidationCss")
#Scripts.Render("~/bundles/formValidation")
HomeController.cs (Addition)
public ActionResult _Add(WebApplication1.Models.Category model)
{
int id;
if (ModelState.IsValid)
{
id = _documentsRepository.SetCategory(model);
}
else
{
ModelState.Clear();
return PartialView(model);
}
return Content(id.ToString());
}
Hope this proves useful to others.
Iam new to .Net MVC. I need to bind data into webgrid return using PartialView(),or
If it is possible to return back using JSON,Now My code will execute on Dropdown change,But it will not bind values in web grid.
JavaScript,Model,Controller Codes are shown below:
Script
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.post('#Url.Action("SelectCustomerByID", "Admin")', {secondValue:firstDDLValue }, function (ReceiptList) {
alert(firstDDLValue);
$('#divgrid').html(ReceiptLists);
});
});
});
</script>
View:
<div id="divgrid" style="margin-top: 15px;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column("Id", "ID", style: "id"),
grid.Column("Cust_Name", "Cust Name", style: "PName"),
grid.Column("Pay_Amount", "Pay_Amount", style: "ICode"),
grid.Column("Pay_Mode", "Pay_Mode", style: "IName"),
grid.Column("Bank_Name", "Bank_Name", style: "Weight"),
grid.Column("Bank_Address", " Bank_Address", style: "MakingCharge"),
grid.Column("ChequeNo", "ChequeNo", style: "Certification"),
grid.Column("Cheque_Date", " Cheque_Date", style: "Price"),
grid.Column("Date", "Date", style: "Price"),
grid.Column("Edit", "", #<a href='../Admin/EditReceipt?id=#item.ID' ><img src="~/Images/edit.png" alt='Edit' /></a>, style: "width:10%"),
grid.Column(header: "Delete", format: #<text><img src="../Images/delete.png" alt='Delete' /></text>) ))
#if (grid.HasSelection)
{
Receipt = (JewellaryWeb.Models.Receipt)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> #Receipt.Id<br />
<b>Name</b> #Receipt.Cust_Name<br />
<b>Amount</b> #Receipt.Pay_Amount<br />
<b>PayMode</b> #Receipt.Pay_Mode<br />
<b>BankName</b> #Receipt.Bank_Name<br />
<b>BankAddress</b> #Receipt.Bank_Address<br />
<b>ChequeNumber</b> #Receipt.ChequeNo<br />
<b>ChequeDate</b> #Receipt.Cheque_Date<br />
}
</div>
Controller:
public ActionResult SelectCustomerByID(Receipt model,string secondValue)
{
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
model.ReceiptList = Receipt.GetReceiptListByCustID(CustID);
return PartialView(model.ReceiptList);
}
I found answer for this I just modified my Script and Use ParitalView to bind data in gird My Solution Code is:
Script
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.get('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
$('#gridContent').html(ReceiptList);
});
});
});
</script>
i create new _Recepitgrid.cshtml as PartialView and write the code for Webgrid as Same as in the main view.
Controller
public ActionResult SelectCustomerByID(Receipt model, string secondValue)
{
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
ReceiptList = Receipt.GetReceiptListByCustID(CustID);
return PartialView("_Recepitgrid", ReceiptList);
}
Now it will works fine..
I have a asp.net MVC View Page which is Master/Detail style.
After reading from this , I realize that I need to serialize jqgrid data before I send to Controller Layer.
[HttpPost]
public ActionResult Detail(Seminar Seminar, List<Seminar_Detail> Seminar_Details)
{
}
So my question is,
1. How could i send data to controller, by using 2 ViewModel classes.
SeminarMaster for Form Input Fields and SeminarDetail for Jqgrid entire rows.
2.If you say, I have only one way which is serializing to jqgrid, then Do i need to serialize Form input fields also?
3.If I have to use serialize way, Do I have chance to use ViewModel classess to parse data to Controller Layer ?
Updated
JqGrid Code or View Layer Implementation
Or Detail Page which user can make Insert/update or delete process.
#model MvcMobile.ViewModel.SeminarListDetailViewModel
#{
ViewBag.Title = "Detail";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Detail</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Seminar</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Seminar_Code)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Seminar_Code)
#Html.ValidationMessageFor(model => model.Seminar.Seminar_Code)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Title)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Title)
#Html.ValidationMessageFor(model => model.Seminar.Title)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Description)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Description)
#Html.ValidationMessageFor(model => model.Seminar.Description)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Room)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Room)
#Html.ValidationMessageFor(model => model.Seminar.Room)
</div>
</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
<script type="text/javascript">
jQuery(document).ready(function () {
var AllSpeakers = (function () {
var list = null;
$.ajax({
'async': false,
'global': false,
'url': 'GetAllSpeakers',
'dataType': 'json',
'success': function (data) {
list = data;
}
});
return list;
})();
var AllTags = (function () {
var list = null;
$.ajax({
'async': false,
'global': false,
'url': 'GetAllTags',
'dataType': 'json',
'success': function (data) {
list = data;
}
});
return list;
})();
var lastSel = 0;
jQuery("#list").jqGrid({
url: '/Seminar/DetailGridData/',
editurl: "/Seminar/MyEdit/",
datatype: 'json',
mtype: 'GET',
colNames: ['Seminar_Code', 'Speaker', 'Tag', 'DateAndTime'],
colModel: [
{ name: 'Seminar_Code', index: 'Seminar_Code', width: 40, align: 'left', editable: true, edittype: "text", editoptions: { size: "35", maxlength: "50"} },
{ name: 'SpeakerID', index: 'SpeakerID', align: 'left', editable: true, edittype: "select", formatter: 'select', editoptions: { value: AllSpeakers,
dataEvents: [
{ type: 'change',
fn: function (e) {
//alert("Speaker change"); // For Cascading Dropdownlist Or Dependent Combo
}
}
]
}, editrules: { required: true}
},
{ name: 'TagID', index: 'TagID', align: 'left', editable: true, edittype: 'select', formatter: 'select', editoptions: { value: AllTags }, editrules: { required: true} },
{ name: 'DateAndTime', index: 'DateAndTime', width: 40, align: 'left', editable: true, edittype: "text", editoptions: { size: "35", maxlength: "50"} }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'SpeakerName',
sortorder: "desc",
viewrecords: true,
autowidth: true,
autoheight: true,
imgpath: '/scripts/themes/black-tie/images',
caption: 'My first grid'
})
$("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, refresh: false, search: false });
$("#list").jqGrid('inlineNav', '#pager', {
addtext: "Add",
edittext: "Edit",
savetext: "Save",
canceltext: "Cancel",
addParams: {
addRowParams: {
// the parameters of editRow used to edit new row
keys: true,
oneditfunc: function (rowid) {
alert("new row with rowid=" + rowid + " are added.");
}
}
},
editParams: {
// the parameters of editRow
key: true,
oneditfunc: function (rowid) {
alert("row with rowid=" + rowid + " is editing.");
}
},
cancelParams: {
key: true,
oneditfunc: function (rowid) {
//alert("row with rowid=" + rowid + " cancel.");
}
}
});
});
</script>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller Layer Code
public class SeminarController : Controller
{
ISeminarListDetailRepository seminarRepository;
//
// Dependency Injection enabled constructors
public SeminarController()
: this(new SeminarListDetailRepository()) {
}
public SeminarController(ISeminarListDetailRepository repository)
{
seminarRepository = repository;
}
/// <summary>
/// Just for Listing page.
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
return View();
}
/// <summary>
/// Master Detail CRUD form according to previous form's choosen code.
/// </summary>
/// <param name="Seminar_Code"></param>
/// <returns></returns>
public ActionResult DetailByCode(string Seminar_Code)
{
return View();
}
/// <summary>
/// Master Detail CRUD form.
/// </summary>
/// <returns></returns>
public ActionResult Detail()
{
var SeminarListDetailViewModel = new SeminarListDetailViewModel();
return View(SeminarListDetailViewModel);
}
/// <summary>
/// It is this method what I really focus when it comes to save all rows of jqgrid at once.
/// </summary>
/// <param name="Seminar"></param>
/// <param name="Seminar_Details"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Detail(Seminar Seminar, List<Seminar_Detail> Seminar_Details)
{
return View();
}
/// <summary>
/// Just for test purpose only.
/// I will not use this method when I know how to save JQGrid's All Rows at once.
/// </summary>
/// <param name="Seminar_Detail"></param>
/// <returns></returns>
public ActionResult MyEdit(Seminar_Detail Seminar_Detail)
{
//var seminar_Code = Seminar_Detail.Seminar_Code;
var jsonData = new
{
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult GetAllSpeakers()
{
string AllSpeakers = " : ;";
var Speakers = seminarRepository.GetAllSpeakerList().Seminar_Item_Speaker;
for (int i = 0; i < Speakers.Count; i++)
{
if (i == Speakers.Count - 1)
{
///For the last row
AllSpeakers += Speakers[i].SpeakerID + ":" + Speakers[i].SpeakerName;
}
else
{
AllSpeakers += Speakers[i].SpeakerID + ":" + Speakers[i].SpeakerName + ";";
}
}
return Json(AllSpeakers, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAllTags()
{
string AllTags = " : ;";
var Tags = seminarRepository.GetAllTagList().Seminar_Item_Tag;
for (int i = 0; i < Tags.Count; i++)
{
if (i == Tags.Count - 1)
{
///For the last row
AllTags += Tags[i].TagID + ":" + Tags[i].TagName;
}
else
{
AllTags += Tags[i].TagID + ":" + Tags[i].TagName + ";";
}
}
return Json(AllTags, JsonRequestBehavior.AllowGet);
}
public ActionResult DetailGridData(string sidx, string sord, int page, int rows)
{
int currentPage = Convert.ToInt32(page) - 1;
int totalRecords = 0;
var SeminarList = seminarRepository.GetSeminarDetail("CMP04").Seminar_Detail; //OrderBy(x => x.Seminar_Code).Skip(page * rows).Take(rows).ToList();
var totalPages = (int)Math.Ceiling(totalRecords / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from s in SeminarList
select new
{
id = s.Seminar_Code + "__" + s.SpeakerID + "__" + s.TagID,
cell = new object[]
{
s.Seminar_Code,
s.SpeakerID,
s.TagID,
s.DateAndTime
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult ListingGridData(string sidx, string sord, int page, int rows)
{
int currentPage = Convert.ToInt32(page) - 1;
int totalRecords = 0;
var SeminarList = seminarRepository.AllSeminarList().Seminar_Masters; //OrderBy(x => x.Seminar_Code).Skip(page * rows).Take(rows).ToList();
var totalPages = (int)Math.Ceiling(totalRecords / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from s in SeminarList
select new
{
id = s.Seminar_Code,
cell = new object[]
{
s.Seminar_Code,
s.Title,
s.Description,
s.Room
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
Updated 2
Please let me make my question more clear.
I have two tables to insert data at once.
1.SeminarMaster(Seminar_Code, Title, Description, Room)
[At Razor View] - Form Input Fields
2.SeminarDetail(Seminar_Code, SpeakerID, TagID, DateAndTime)
[At Razor View] - JQGrid Rows and Columns
These two tables are in one-to-many relationship.
Update 3
I am really sorry for making my question unclear again and again.
Now please read my update again.I tried my best to make you clear understand my question.
Index.cshtml Or First time display form which user can select any row and go to detail page to make update.But Actually, below razor is not complete yet. Because I need to add Edit buttons at every rows of jqgrid. That Edit button will redirect to another page that I called Detail.cshtml by parsing selected Code. I will update it later. It is not my main problem.
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Seminar List</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
#Html.ActionLink("Click here", "Detail") to add new data.
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Seminar/ListingGridData/',
editurl: "/Seminar/MyEdit/",
datatype: 'json',
mtype: 'GET',
colNames: ['Seminar_Code', 'Title', 'Description', 'Room'],
colModel: [
{ name: 'Seminar_Code', index: 'Seminar_Code', width: 40, align: 'left', editable: false },
{ name: 'Title', index: 'Title', width: 40, align: 'left', editable: false },
{ name: 'Description', index: 'Description', width: 40, align: 'left', editable: false },
{ name: 'Room', index: 'Room', width: 40, align: 'left', editable: false }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Title',
sortorder: "asc",
viewrecords: true,
autowidth: true,
autoheight: true,
caption: 'Seminar List - Grid'
})
});
</script>
Every suggestion will be appreciated.