- Download Visual Studio?
- Login Instructions
- CRUD Operation using Ajax/Json Code
- Read Data from database and Show in HTML Table using Ajax/JSON
- Select2 ComboBox
- Show Current Date in Input Type date when view is loaded
- Assign Date to Html Input Type Date return from database usign Ajax/JSON
- Show Date in HTML return from database usign Ajax/JSON
- Bootstrap Model
- Cache in Asp.net MVC
- Print Report
- Master Page
- LogOut (when Cache is used)
2. Login Code and Instructions
Keep this code in web.config just after this code:
<authentication mode="Forms">
<forms loginurl="Home/Login1" defaulturl="~/" timeout="30" slidingexpiration="true"></forms>
</authentication>
Login View
@using (Html.BeginForm("Login", "Admin", new { returnUrl = Request.QueryString["returnUrl"] }, FormMethod.Post))
{ --Html Design here }
Code When click on Login Button
if (db.AccountManagements.Any(x => x.userName1 == username1 && x.password1 == PWrod && x.active == "Yes") == true)
{
//return Role
FormsAuthentication.SetAuthCookie(username1, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
//goto menu
return RedirectToAction("", "");
}
}
else
{
ViewBag.messag = "Invalid Username | Password Or Temporarily ";
return View();
}
3. Create / Read / Update / Delete data using Jquery/Ajax/Json
View Code
$.get("/FeesC/Delete_InvoiceNo", { Invo: $("#InvoiceNo5").val() }, function (data)
{
$("#messageSF").text(data);
});
Controller Code
public JsonResult ReturnData(int Invo)
{
var a=db.FeesSaveds.Find(Invo);
return Json(a, JsonRequestBehavior.AllowGet);
}
4. Read Data from database and Show in HTML Table using Ajax/JSON
HTML Code
<div style="overflow-y:auto;width:100%;">
<p id="totalrecord" style="margin:0px;" class="float-end"></p>
<table class="table table-bordered" id="mytable" cellpadding="0" cellspacing="0">
<thead style="padding:0px;">
<tr style="padding: 0px; text-align: center; background-color: #80dfff; border: 1px solid black;">
<th style="padding:0px;">S.No</th>
<th style="padding:0px;">Type</th>
<th style="padding:0px;">Account Title</th>
<th style="padding:0px;">Code</th>
<th style="padding:0px;">Actions</th>
<th style="padding:0px;">SMS</th>
</tr>
</thead>
</table>
</div>
JQuery Code
$("#mytable tr:gt(0)").remove();
$.get("/AdminJson/loadaccounts", { option: txt, search: search1 }, function (data) {
var RowCount = 0;
var row;
$.each(data, function (i, v1) {
RowCount += 1;
row += "<tr style='padding:0px; margin:0px;text-align:center;border:1px solid black;'><td style='padding:0px; margin:0px;border:1px solid black;'> " + RowCount + " </td> <td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.typee + "</td> <td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.name + "</td> <td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.code + "</td><td style='padding:0px; margin:0px;border:1px solid black;'>" + v1.AdminId + "</td><td style='padding:0px; margin:0px;border:1px solid black;'> <> <a title='Edit Record' style=' font-size:18px;margin-left:10px;' onclick=Edit2(" + v1.id + ") ><span class='fa fa-edit'></span></a> <a title='Delete Record' style='margin-left:10px; font-size:18px;' onclick=Delete1(" + v1.id + ") ><span class='fa fa-trash'></span></a> </td><td>< ></td ></tr > ";
});
$("#mytable").append("<tbody style='margin:0px; padding:0px;'> " + row + "</tbody>");
$("#totalrecord").text("Total Accounts : " + RowCount);
$("#divLoader1").hide();
});
Controller Code
public JsonResult loadaccounts(string option,string search)
{
var a = db.accounts.Where(x => x.AdminId == AdminId && x.BranchId == branchId).OrderByDescending(x => x.dte).Take(50).ToList();
return Json(a, JsonRequestBehavior.AllowGet);
}
5. Select2, Searchable ComboBox
1. First Download Library
Download Select2 Library
Note: Consider only dist folder (ignore other files)
2. Reference Library in your project
Reference these three files in the view page, but make sure the JQuery file must be referenced once,
if you reference JQuery file in master page then the Select2 will not work
keep these three files in every view page, where you need to use Select2
<script src="~/Scripts/jquery-1.8.0.min.js"></script>
<link href="~/Scripts/SmartCombo/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/SmartCombo/js/select2.min.js"></script>
3. HTML Code
<select class="js-example-basic-single" id="bcategorycombo" style="width: 100%; ">
</select>
4. Jquery Code (to load items to combobox from database)
<script>
$(document).ready(function () {
LoadCategory();
$("#bcategorycombo").select2({ theme: "classic" });
$("#bcategorycombo").css({ "font-size": "40px" });
});
function LoadCategory() {
$.get("/COmboJson/loadCategory", {}, function (data) {
var itemZ = "";
$.each(data, function (i, v1) {
itemZ += '<option value="' + v1.category + '">' + v1.category + '</option>';
});
$("#bcategorycombo").append(itemZ);
});
}
</script>
5. Controller Code
/controller code
public JsonResult loadCategory()
{
int AdminId = rt.Return_MainID(User.Identity.Name);
int branchid = rt.Return_BranchId(User.Identity.Name);
var ab = db.category1.Where(x => x.AdminId == AdminId && x.BranchId == branchid).ToList();
return Json(ab, JsonRequestBehavior.AllowGet);
}
6. Show Current Date in Input Type date when view is loaded
HTML Code
<input type="date" id="bdate2" class="form-control" value=@ViewBag.dateCurrent />
Controller Code
Publick ActionResult index()
{
ViewBag.dateCurrent = rt.Return_DateHTML(DateTime.Now);
}
string mm3, dd3;
public string Return_DateHTML(DateTime dt)
{
if (dt.Month < 10)
{
mm3 = "0" + dt.Month;
}
else
{
mm3 = dt.Month.ToString();
}
if (dt.Day < 10)
{
dd3 = "0" + dt.Day;
}
else
{
dd3 = dt.Day.ToString();
}
return (dt.Year + "-" + mm3 + "-" + dd3); //
}
7. Assign Date to Html Input Type Date return from database usign Ajax/JSON
Create Function in Jquery and use the last line to assign the value
JQuery Code
//Jquery Code
function dateFormatHtml(d) {
console.log(d);
return d.getFullYear()+ "-"
+ ((d.getMonth() + 1) + "").padStart(2, "0")
+ "-" + (d.getDate() + "").padStart(2, "0");
}
$("#ToDate").val(dateFormatHtml(new Date(parseInt((v1.ToDate).match(/\d+/)[0]))));
8. Show Date in HTML return from database usign Ajax/JSON
JQuery Code
function dateFormat(d) {
console.log(d);
return (
(d.getDate() + "").padStart(2, "0")
+ "/" + (d.getMonth() + 1) + "").padStart(2, "0")
+ "/" + d.getFullYear();
}
dateFormat(new Date(parseInt((v1.datee).match(/\d+/)[0])))
9. Show a Model in Asp.net MVC
HTML Code
<div class="modal fade" id="myModelListInvoices30" role="dialog">
<div class="modal-dialog" style="max-width: 70%!important;" role="document">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Last 50 Saved Invoices</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JQuery Code (open model from JQuery)
new bootstrap.Modal($('#myModelListInvoices30')).show();
OR
$('#myModal').modal('show')
10. Show a Model in Asp.net MVC
Waht is Cache? It prevent the application to retreive all the html/images etc from server again and again, it saves the data in client browser, and when it is required, the data is retrieved from the client browser, This process increase the application performance
Keep this line above controller, all views of the controller will be cached
Keep this line above view, that view will be cached
Controller Code
[OutputCache(Duration = 10800, Location = System.Web.UI.OutputCacheLocation.Client, VaryByParam = "TempData['user']", VaryByContentEncoding = "none")]
To Disable Cache for a view, Use this Code
Controller Code
[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] //no cache for this page
11. LogOut
1) Create a view in any controller, call this view, when logout button is clicked
HTML Code (call logout view)
<li><a href=@Url.Action("LogOut", "AdminMenu") <span class="fa fa-book" ></span>LogOut</a></li>
Controller Code
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
return RedirectToActionPermanent("Login", "Account");
}
2) Keep this code in every Json Result Function
Controller Code
if (User.Identity.IsAuthenticated == false)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
3. Keep this code in every Action Result View
Controller Code
if (User.Identity.IsAuthenticated == false)
{
return RedirectToAction("Login", "Account");
}
3) In every view page, keep this JQuery Code, this code will call to a function in controller
JQuer Code
<script>
CheckUser();
function CheckUser() {
$.get("/JsonUserRoles/UserCheck", {}, function (data) {
if (data == "Login") {
window.location.href = "/Account/Login";
}
});
}
</script>
Controller Code (this function will be called)
[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] // this is required
public JsonResult UserCheck()
{
if(User.Identity.IsAuthenticated==false)
{
//redirect to loginpage
return Json("Login", JsonRequestBehavior.AllowGet);
}
else
{
//dont redirect to LoginPage
return Json("", JsonRequestBehavior.AllowGet);
}
}
Print Report using Jquery
HTML Code
<input type="button" name="Save" value="Print" onclick="print()" class="button3 btn-info" />
<div style="overflow:auto; ">
<table id="ttable" class="table table-bordered table-sm" style="overflow:auto;border-color:black;padding:0px;font-size:medium;width:100%; " cellspacing="0">
<thead>
<tr style="padding:0px; text-align:center;">
<th style="width: 10%; padding: 0px;" colspan="5">
@*~/SavedImages/asanicalogo.png*@
<img src="" style="height:100px; width:100px;float:left;margin-top:13px;" id="shoplogo" />
<div class="" style="float:left;margin-left:10px; margin-top:4px;">
<h1 style="text-align:left;margin:0px; margin-top:10px;" id="shopname"></h1>
<h5 style="text-align:left;margin:0px;" id="shopaddress"></h5>
<h5 style="text-align:left;margin:0px;" id="emailaddress"></h5>
<h5 style="text-align:left;margin:0px;" id="shopcontact"></h5>
</div>
</th>
</tr>
</thead>
</table>
</div>
JQuery Code
function print() {
var divToPrint = document.getElementById("ttable");
newWin = window.open("PRINT");
newWin.document.write(divToPrint.outerHTML);
setTimeout(function () {
newWin.print();
}, 500)
}
Master Page
1) Right Click on View Folder > New Item > View , Name view
_ViewStart
2) Paste this code insdide view (Clear it first)
@{
Layout = "~/Views/Shared/_layoutPage.cshtml";
}
3) Right Click on View Folder > New > Add Folder (and name it Shared)
4) Right Click on This Shared Folder inside View Folder Select Add New > View > (name it _LayoutPage)
5) Keep this code in _LayoutPage view (where you want the child view will be showing
@RenderBody()