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.
Related
I needed to create a search page where various types of text, dropdown, date field will be there. i added onkeyup function to every text field so that whenever i put any text or number a grid will appear with subgrid. The issue i am facing is if i give input for the first time then the grid appear with correct data. if i clear that field then the grid is reloading also but if i input again in that field or any other text field then the js is not sending request to the action method with updated post value.
Here is my View Part:
<section class="content">
<div class="container-fluid">
<!-- SELECT2 EXAMPLE -->
<!-- SELECT2 EXAMPLE -->
<div class="card card-info">
<div class="card-header">
<h3 class="card-title">Search Criteria</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<!-- /.card-header -->
#using (Html.BeginForm("SearchReport", "LRLiveSearch", FormMethod.Post))
{
<div class="card-body">
<div class="row">
<div class="col-md-12" style="line-height:1.50px;">
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label>Deed No</label>
#Html.TextBoxFor(model => model.DeedNo, new { #class = "form-control", onkeyup = "LiveSearch('DN', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Deed Identity</label>
#Html.TextBoxFor(model => model.DeedId, new { #class = "form-control", onkeyup = "LiveSearch('DI', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Client Name</label>
#Html.TextBoxFor(model => model.ClientName, new { #class = "form-control", onkeyup = "LiveSearch('CN', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Client Contact Number</label>
#Html.TextBoxFor(model => model.ClientPhoneNumber, new { #class = "form-control", onkeyup = "LiveSearch('CP', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>MR No</label>
#Html.TextBoxFor(model => model.MRNo, new { #class = "form-control", onkeyup = "LiveSearch('MR', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Cheque No</label>
#Html.TextBoxFor(model => model.ChequeNo, new { #class = "form-control", onkeyup = "LiveSearch('CQN', this.value)" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label>Collection Type</label>
#Html.DropDownListFor(model => model.CollectionType, Model.CollectionTypeList, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>From Date</label>
<div class="input-group date" id="FirstDate" data-target-input="nearest">
#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control datetimepicker-input", #data_target = "#FirstDate" })
<div class="input-group-append" data-target="#FirstDate" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>To Date</label>
<div class="input-group date" id="SecondDate" data-target-input="nearest">
#Html.TextBoxFor(model => model.ToDate, new { #class = "form-control datetimepicker-input", #data_target = "#SecondDate" })
<div class="input-group-append" data-target="#SecondDate" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
#*<div class="col-md-1">
<div class="form-group">
<center>
<button id="btnLRSearch" formaction="SearchList" class="btn btn-md btn-primary" style="margin-top:.80rem" type="button">Search</button>
</center>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<center>
<button id="btnPrint" formaction="SearchReport" class="btn btn-md btn-warning" style="margin-top:.80rem" type="submit">Report</button>
</center>
</div>
</div>*#
</div>
</div>
</div>
</div>
}
</div>
</div>
<!-- /.container-fluid -->
<table class="table table-bordered table-striped table-hover text-nowrap text-sm" id="Demogrid"></table>
<div class="container-fluid" id="pager"></div>
</section>
here is my JS part where i handled onkeyup event:
function LiveSearch(type, value) {
var searchType = type;
var searchValue = value;
if (value == "" || value == null) {
$("#Demogrid").jqGrid('setGridParam', { postData: { Type: searchType, SearchValue: searchValue } }).trigger('reloadGrid');
return true;
}
else {
$("#Demogrid").jqGrid({
url: '/HRM/LRLiveSearch/LiveSearch',
datatype: "json",
mtype: 'Get',
//table header name
colNames: ['ProjectName', 'PlotName', 'TotalLandArea', 'DeedId', 'DeedDate', 'RentFeeType', 'RentFee', 'ClientName', 'ClientAddress', 'ClientContactNo', 'EffectiveDate'],
//colModel takes the data from controller and binds to grid
colModel: [
{ name: "ProjectName" },
{ name: "PlotName" },
{ name: "TotalLandArea" },
{ name: "DeedId" },
{ name: "DeedDate" },
{ name: "RentFeeType" },
{ name: "RentFee" },
{ name: "ClientName" },
{ name: "ClientAddress" },
{ name: "ClientContactNo" },
{ name: "EffectiveDate" }
],
height: '100%',
viewrecords: true,
caption: 'Deed Info',
emptyrecords: 'No records',
rowNum: 10,
pager: jQuery('#pager'),
rowList: [10, 20, 30, 40],
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
postData: {
Type: searchType,
SearchValue: searchValue
},
autowidth: true,
subGrid: true,
subGridRowExpanded: function (subgridId, rowId) {
// create the subgrid HTML here
var subgridTableId = subgridId + "_t";
$("#" + subgridId).html("<table id='" + subgridTableId + "'></table>");
// get the data for the parent row
var parentRowData = $("#Demogrid").jqGrid("getRowData", rowId);
// retrieve the primary key value of the parent row
var parentId = parentRowData.DeedId;
$("#" + subgridTableId).jqGrid({
// configure the subgrid
url: '/HRM/LRLiveSearch/LiveSearch',
datatype: "json",
mtype: 'Get',
//table header name
colNames: ['CollectionId', 'CollectionDate', 'MRIdentity', 'MRNo', 'MRDate', 'MRType', 'CollectionType', 'ChequeNo', 'BankName'],
//colModel takes the data from controller and binds to grid
colModel: [
{ name: "CollectionId", hidden: true },
{ name: "CollectionDate" },
{ name: "MRIdentity" },
{ name: "MRNo" },
{ name: "MRDate" },
{ name: "MRType" },
{ name: "CollectionType" },
{ name: "ChequeNo" },
{ name: "BankName" }
],
height: '100%',
viewrecords: true,
caption: 'Collection Details',
emptyrecords: 'No records',
rowNum: 10,
jsonReader: {
repeatitems: false
},
postData: {
Type: searchType,
SearchValue: searchValue,
DeedId: parentId
},
autowidth: true
});
},
}).navGrid('#pager',
{
edit: true,
add: true,
del: true,
search: true,
refresh: true,
closeAfterSearch: true
});
}
}
and it is my action method:
public JsonResult LiveSearch(string sord, int page, int rows, string searchString, string Type, string SearchValue, string DeedId)
{
if(SearchValue == "")
{
SearchValue = "$";
}
var query = iLRSearchRepository.LiveSearchFilter(Type, SearchValue);
if (DeedId == null)
{
//#2 Setting Paging
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
//#3 Linq Query to Get Data
var Results = query.Select(
x => new
{
ProjectName = x.ProjectName,
PlotName = x.PlotName,
TotalLandArea = x.TotalLandArea,
DeedId = x.DeedId,
DeedDate = x.DeedDate.ToString("dd/MM/yyyy"),
RentFeeType = x.RentFeeType,
RentFee = x.RentFee,
ClientName = x.ClientName,
ClientAddress = x.ClientsAddress,
ClientContactNo = x.ClientsContactNo,
EffectiveDate = x.ActivateDate.ToString("dd/MM/yyyy")
}).Distinct();
//#4 Get Total Row Count
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
//#5 Setting Sorting
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.DeedId);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.DeedId);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
//#6 Setting Search
if (!string.IsNullOrEmpty(searchString))
{
Results = Results.Where(m => m.DeedId == searchString);
}
//#7 Sending Json Object to View.
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
else
{
var Results = query.Where(x => x.DeedId == DeedId).Select(
x => new
{
CollectionId = x.CollectionId,
CollectionDate = x.CollectionDate?.ToString("dd/MM/yyyy"),
MRIdentity = x.MRIdentity,
MRNo = x.MRNo,
MRDate = x.MRDate?.ToString("dd/MM/yyyy"),
MRType = x.MRType,
CollectionType = x.CollectionType,
ChequeNo = x.ChequeNo,
BankName = x.BankName,
});
var jsonData = new
{
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
//model.landRent_View_SearchInfos = query;
//return View("_LandRentInfoList", model);
}
With your code you every time try create jqGrid when you do a search, which of course is not allowed since the grid is already created.
if (value == "" || value == null) {
$("#Demogrid").jqGrid('setGridParam', { postData: { Type: searchType, SearchValue: searchValue } }).trigger('reloadGrid');
return true;
}
else {
$("#Demogrid").jqGrid({}...)
}
To solve the problem first create the grid and the do a reload when the value changes
$("#Demogrid").jqGrid({
url: '/HRM/LRLiveSearch/LiveSearch',
datatype: "json",
mtype: 'Get',
//table header name
...
});
function LiveSearch(type, value) {
var searchType = type;
var searchValue = value;
$("#Demogrid").jqGrid('setGridParam', { postData: { Type: searchType, SearchValue: searchValue } }).trigger('reloadGrid');
return true;
}
Hope this helps.
Initially you can set values (postData) so that the grid return empty data or create the grid with empty local data (datatype : local) and then change the datatype to json.
I'm creating a web site, where I have a list of classes, and I want that each class will have it`s own calendar. What I mean is, when I click button 1, I will go to a separate calendar then button 2 and so on.
I already have a working calendar, I just don't understand how assign to each button a calendar.
So I have a working calendar with options of add/delete/update events, but I don't understand how to connect them.
I'm on this problem over a week now, and I couldn't find any solution. help please.
This is the index.cshtml where the classes are created: (classes view)
#model IEnumerable<ClasSaver.Models.ClassesModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<style>
.button {
background-color: deepskyblue; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Building)
</th>
<th>
#Html.DisplayNameFor(model => model.How_Many_In_Class)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Building)
</td>
<td>
#Html.DisplayFor(modelItem => item.How_Many_In_Class)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
<input id="#item.Id" type="button" onclick="parent.open('https://www.google.com/')" value="Open in new window" class="button">
</td>
</tr>
}
</table>
<script>
</script>
and the controller
using ClasSaver.Data;
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class ClassesController : Controller
{
// GET: Classes
public ActionResult Index()
{
List<ClassesModel> classes = new List<ClassesModel>();
ClassDAO classDao = new ClassDAO();
classes = classDao.FetchAll();
return View("Index",classes);
}
public ActionResult Details(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("Details", classes);
}
public ActionResult Create(ClassesModel classesModel)
{
return View("ClassesForm", classesModel);
}
[HttpPost]
public ActionResult ProcessCreate(ClassesModel classesModel)
{
//save to DB
ClassDAO classesDAO = new ClassDAO();
classesDAO.CreateOrUpdate(classesModel);
return View("Details", classesModel);
}
public ActionResult Edit(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("ClassesForm", classes);
}
public ActionResult Delete(int id)
{
ClassDAO classesDAO = new ClassDAO();
classesDAO.Delete(id);
List<ClassesModel> classes = classesDAO.FetchAll();
return View("Index", classes);
}
public ActionResult SearchForm()
{
return View("SearchForm");
}
[HttpPost]
public ActionResult searchForName(string searchPhrase)
{
ClassDAO classesDAO = new ClassDAO();
List<ClassesModel> searchResults = classesDAO.SearchForName(searchPhrase);
return View("Index", searchResults);
}
}
}
and this is where the calendar is created index.cshtml: (home view)
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<button id="btnDelete" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-remove"></span> Remove
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Save Event</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="hdEventID" value="0" />
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.EventID,
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' + calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
eventID: 0,
title: '',
description: '',
start: start,
end: end,
allDay: false,
color: ''
};
openAddEditForm();
$('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
EventID: event.eventID,
Subject: event.title,
Start: event.start.format('DD/MM/YYYY HH:mm A'),
End: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
ThemeColor: event.color,
IsFullDay: event.allDay
};
SaveEvent(data);
}
})
}
$('#btnEdit').click(function () {
//Open modal dialog for edit event
openAddEditForm();
})
$('#btnDelete').click(function () {
if (selectedEvent != null && confirm('Are you sure?')) {
$.ajax({
type: "POST",
url: '/home/DeleteEvent',
data: { 'eventID': selectedEvent.eventID },
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModal').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
$('#dtp1,#dtp2').datetimepicker({
format: 'DD/MM/YYYY HH:mm A'
});
$('#chkIsFullDay').change(function () {
if ($(this).is(':checked')) {
$('#divEndDate').hide();
}
else {
$('#divEndDate').show();
}
});
function openAddEditForm() {
if (selectedEvent != null) {
$('#hdEventID').val(selectedEvent.eventID);
$('#txtSubject').val(selectedEvent.title);
$('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
$('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
$('#chkIsFullDay').change();
$('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
$('#txtDescription').val(selectedEvent.description);
$('#ddThemeColor').val(selectedEvent.color);
}
$('#myModal').modal('hide');
$('#myModalSave').modal();
}
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
var data = {
Id: $('#hdEventID').val(),
Subject: $('#txtSubject').val().trim(),
Start: $('#txtStart').val().trim(),
End: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
Description: $('#txtDescription').val(),
ThemeColor: $('#ddThemeColor').val(),
IsFullDay: $('#chkIsFullDay').is(':checked')
}
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
</script>
}
and the controller
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetEvents()
{
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var events = dc.Events.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
[HttpPost]
public JsonResult DeleteEvent(int eventID)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
I want to load some element from database and next after click button load more elements. In Controller my code looks like:
public ActionResult GetData(int currentIndex, int elementsNumber)
{
var query = (from restauracja in _context.Restauracja
select restauracja).Skip(currentIndex * elementsNumber)
.Take(elementsNumber).ToList();
var list = JsonConvert.SerializeObject(query,
Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
}
In View i have this:
$("#next").click(function () {
GetData();
});
function GetData() {
var currentIndex2 = 1;
var elementsNumber2 = 3;
$.ajax({
type: "POST",
url: 'Restauracja/GetData',
data: { currentIndex: currentIndex2, elementsNumber: elementsNumber2 },
dataType: "json",
success:
error: function () { alert('Niesukces'); },
});
}
Now, in success: i must generate html like this
<div class="box_list isotope-item popular">
<div class="row no-gutters">
<div class="col-lg-5">
<figure>
<small>#item.Kategoria</small>
<a href="#Url.Action("Szczegoly","restauracja", new { id = item.IdRestauracji },
null) ">#if (item.ObrazekWyrozniajacy != null)
{<img src="data:image/jpeg;base64,#Convert.ToBase64String(item.ObrazekWyrozniajacy)"
class="img-fluid" alt="" width="800" height="533">}<div class="read_more">
<span>Sprawdź lokal</span></div></a>
</figure>
</div>
<div class="col-lg-7">
<div class="wrapper">
<h3>#Html.ActionLink(item.NazwaObiektu, "Szczegoly", "Restauracja", new { id = item.IdRestauracji }, null) #item.Ulica #item.NumerLokalu, #item.Miejscowosc</h3>
<p>#item.Zajawka</p>
<span class="price">From <strong>$54</strong> /per person</span>
</div>
<ul>
<li><i class="ti-eye"></i> 164 views</li>
<li><div class="score"><span>Superb<em>350 Reviews</em></span><strong>8.9</strong></div></li>
</ul>
</div>
</div>
</div>
This code is not that bad yet, because I can convert it to html, e.g.:
success: function (data) {
for (var i = 0; i < data.length; i++) {
var encodedString = btoa(data[i].ObrazekWyrozniajacy);
var html = [
'<div class="box_list isotope-item popular">',
'<div class="row no-gutters">',
'<figure>',
'<small>' + data[i].Kategoria + '</small>',
'<a href="#Url.Action("Szczegoly","restauracja", new { id = "-1" }, null) ">',
'#if ("-2" != null){<img src="data:image/jpeg;base64,-3" class="img-fluid" alt="" width="800" height="533" >}',
'<div class="read_more"><span>Sprawdź lokal</span></div></a >',
'</figure >',
'</div>',
'<div class="col-lg-7">',
'<div class="wrapper">',
'',
'<h3>' + data[i].Ulica + data[i].NumerLokalu + data[i].Miejscowosc + '</h3>',
'<p>' + data[i].Zajawka + '</p>',
'<span class="price">From <strong>$54</strong> /per person</span>',
'</div>',
'<ul>',
'<li><i class="ti-eye"></i> 164 views</li>',
'<li><div class="score"><span>Superb<em>350 Reviews</em></span><strong>8.9</strong></div></li>',
'</ul>',
'</div>',
'</div>',
'</div>',
].join("\n");
$(".isotope-wrapper").append(html);
However, in the database I store images in the form of byte []. Can I convert them somehow differently? Or do it differently?
Instead of returning a hard coded html, you can return a partial view as below:
Create the partial view for ajax response:
<!-- RestauracjaPartial.cshtml -->
<!-- Model is the same as the main page -->
#model IndexModel
#foreach(var item in Model)
{
<div class="box_list isotope-item popular">
<div class="row no-gutters">
<div class="col-lg-5">
<figure>
<small>#item.Kategoria</small>
<a href="#Url.Action("Szczegoly","restauracja", new { id = item.IdRestauracji },
null) ">#if (item.ObrazekWyrozniajacy != null)
{<img src="data:image/jpeg;base64,#Convert.ToBase64String(item.ObrazekWyrozniajacy)"
class="img-fluid" alt="" width="800" height="533">}<div class="read_more">
<span>Sprawdź lokal</span></div></a>
</figure>
</div>
<div class="col-lg-7">
<div class="wrapper">
<h3>#Html.ActionLink(item.NazwaObiektu, "Szczegoly", "Restauracja", new { id = item.IdRestauracji }, null) #item.Ulica #item.NumerLokalu, #item.Miejscowosc</h3>
<p>#item.Zajawka</p>
<span class="price">From <strong>$54</strong> /per person</span>
</div>
<ul>
<li><i class="ti-eye"></i> 164 views</li>
<li><div class="score"><span>Superb<em>350 Reviews</em></span><strong>8.9</strong></div></li>
</ul>
</div>
</div>
</div>
}
And modify the backend method as below:
public ICollection<Restauracja> Items { get; set; }
public IActionResult GetData(int currentIndex, int elementsNumber)
{
Items = from restauracja in _context.Restauracja
select restauracja).Skip(currentIndex * elementsNumber)
.Take(elementsNumber).ToList();
return new PartialViewResult()
{
ViewName = "RestauracjaPartial",
ViewData = this.ViewData
};
}
There is a button on the page.
I do not see this button in the page code.
Question: how to determine the origin of a button in a view?
The project is used - ImportExportExcelASPNetCore // talkingdotnet // github.com
After starting the application, a page will appear.
Where in the page code is the Выберите файл button?
Code
#page
#model ImportExportExcelASPNetCore.Pages.ImportExportModel
#{
ViewData["Title"] = "ImportExport";
}
<h2>Import Export using NPOI</h2>
<form method="post" enctype="multipart/form-data">
<br/>
<div class="row">
<div class="col-md-4">
<input type="file" id="fUpload" name="files" class="form-control" />
</div>
<div class="col-md-8">
<input type="button" id="btnUpload" value="Upload" />
</div>
</div>
<div class="row">
<div class="col-md-8" style="padding-top:10px;">
<button asp-page-handler="Export">Export</button>
</div>
</div>
<br/>
<div id="dvData"></div>
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript" language="JavaScript">
$(document).ready(function ()
{
$('#btnUpload').on('click', function ()
{
var fileExtension = ['xls', 'xlsx']; // Расширение файла
var filename = $('#fUpload').val(); // Имя файла
if (filename.length == 0)
{
alert("Please select a file.");
return false;
}
else
{
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1)
{
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fUpload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax(
{
type: "POST",
url: "/ImportExport?handler=Import",
beforeSend: function (xhr)
{
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response)
{
if (response.length == 0)
alert('Some error occured while uploading');
else
{
$('#dvData').html(response);
}
},
error: function (e)
{
$('#dvData').html(e.responseText);
}
});
})
});
</script>
}
This is my controller.
public class DokuzasController : Controller
{
schoolEntities se = new schoolEntities();
public ActionResult Index()
{
IEnumerable<DersViewModel> leclist;
HttpResponseMessage responselec = GlobalVariables.LecturesClient.GetAsync("dokuzas").Result;
leclist = responselec.Content.ReadAsAsync<IEnumerable<DersViewModel>>().Result;
return View(leclist);
}
public ActionResult AddOrEdit()
{
List<ders> dersList = se.ders.ToList();
ViewBag.dersList = new SelectList(dersList, "DersID", "Ders1");
return View();
}
public JsonResult GetDersList(int DersID)
{
se.Configuration.ProxyCreationEnabled = false;
List<saat> saatList = se.saat.Where(x => x.DersID == DersID).ToList();
return Json(saatList, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel lec)
{
if (lec.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", lec).Result;
TempData["SuccessMessage"] = "Kaydedildi.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + lec.LectureId, lec).Result;
TempData["SuccessMessage"] = "Güncellendi.";
}
return RedirectToAction("Index");
}
}
And this is AddOrEdit part.
#model Mvc.Models.DersViewModel
<div class="container">
<div class="form-group">
#if (ViewBag.dersList != null)
{
#Html.DropDownListFor(model => model.DersID, ViewBag.dersList as SelectList, "--Lecture--", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.SaatID, new SelectList(" "), "--Time--", new { #class = "form-control" })
</div>
</div>
#using (Html.BeginForm())
{
<div class="form-group">
<input type="submit" value="Kaydet" class="btn button" />
<input type="reset" value="Sil" class="btn button" />
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#DersID").change(function () {
$.get("/Dokuzas/GetDersList", { DersID: $("#DersID").val() },
function (data) {
$("#SaatID").empty();
$.each(data, function (index, row) {
$("#SaatID").append("<option value='" + row.SaatID + "'>" + row.Saat1 + "</option>");
});
});
});
});
</script>
I create a cascading dropdown list for lecture and time but i cannot save it to the table. When i choose items and select submit button i can submit only null to the table. It did not save what i choose from the dropdownlist. How can i save from my cascading dropdown list to the table?
Your Dropdowns are not inside your Form, so they are not included in the post. Try the below code for your view.
#model Mvc.Models.DersViewModel
#using (Html.BeginForm())
{
<div class="container">
<div class="form-group">
#if (ViewBag.dersList != null)
{
#Html.DropDownListFor(model => model.DersID, ViewBag.dersList as SelectList, "--Lecture--", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.SaatID, new SelectList(" "), "--Time--", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Kaydet" class="btn button" />
<input type="reset" value="Sil" class="btn button" />
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#DersID").change(function () {
$.get("/Dokuzas/GetDersList", { DersID: $("#DersID").val() },
function (data) {
$("#SaatID").empty();
$.each(data, function (index, row) {
$("#SaatID").append("<option value='" + row.SaatID + "'>" + row.Saat1 + "</option>");
});
});
});
});
</script>