How to optimise my partial view loading time? (C#, MVC, jQuery) - javascript

For this feature, I want the respective tour package details (partial view.cshtml) to load in the main view (view.cshtml) as I select the different options. The problem I am facing now is that, the partial view content loads way too slowly.
For example,
Tour A package detail: New Zealand Tour (16 Day)
Tour B pacakage detail: New Zealand Tour (14 Day)
if i click onto card A, it takes a long time for New Zealand Tour (16 Day) to appear
if i click onto card B, New Zealand Tour (16 Day) will still be there, only after a long time of waiting, then it will switch to New Zealand Tour (14 Day)
sorry i tried to attach the gif demo but it doesn't allow me to upload
here are my codes:
View.cshtml
#using StiWebsite.Models;
#using System.Security.Policy
#model dynamic
#{
ViewData["Title"] = "Experiential";
}
<div class="row addCss3" style="padding: 0 1rem" id="paddingRow">
<div class="col-sm-12 col-xs-12 col-md-12 col-lg-12">
<div class="row filterPart">
<div class="dropdown filter imm" id="ddlFilter" style="z-index: 2">
<select id="studyTourFilter" class="form-control selectpicker">
<option class="worldSelect" value="" data-content="<img id='studyTourFilterIcon' class='img-responsive icon' src='/assets/img/immigration/flag/world.png'></img> Select Country">Select Country</option>
#foreach (Country country in Model.countryL)
{
#if (country.CountryID == "AUEXP" || country.CountryID == "CAEXP" || country.CountryID == "ITEXP"
|| country.CountryID == "NZEXP" || country.CountryID == "SGEXP" || country.CountryID == "SPEXP")
{
<option id="studyTourOption" value="#Url.Content(country.CountryID)" data-content="<img id='studyTourFilterIcon' class='img-responsive icon' src='#Url.Content(country.CountryImg)'></img> #Url.Content(country.CountryName)">#country.CountryName</option>
}
}
</select>
#foreach (Country country in Model.countryL)
{
#if (country.CountryID == "AUEXP" || country.CountryID == "ITEXP" || country.CountryID == "NZEXP" || country.CountryID == "SGEXP" || country.CountryID == "SPEXP")
{
<div id="tourSelect-#Url.Content(country.CountryID)" class="tourSelect hidden">
<div class="row expcaurosel">
<p id="cauroTitle" class="card-title">Our Packages</p>
#foreach (StudyTour tour in Model.studyTourL)
{
#if (tour.CountryID == country.CountryID)
{
<div class="col-sm-6 col-xs-6 col-md-4 col-lg-4 expCard">
<button id="cauroLinkBtn" type="button" href="#Url.Action("tourPackage", "Experiential", new {id = tour.StudyTourID})" data-toggle="modal" data-target="#staticBackdrop">
#Html.Raw(tour.StudyTourContent)
</button>
</div>
}
}
</div>
</div>
}
}
</div>
</div>
</div>
</div>
<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><img class="img-responsive" src="/assets/img/experiential/icon/7.png"></span>
</button>
</div>
<div class="modal-body">
**PARTIAL VIEW APPEAR HERE**
<div id="partialView"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts {
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/jscript">
$(document).ready(function(){
$("div>button").click(function (e) {
e.preventDefault();
$("#partialView").load($(this).attr("href"));
});
});
</script>
}
Partial View cshtml
#using StiWebsite.Models;
#using System.Security.Policy
#model StudyTourImgPackage;
#{
ViewData["Title"] = "Tour Package Details";
}
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="row title" id="progTitle" style="display: block;">
<div id="packageProgram" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="background-color: #fafafa; overflow: hidden">
#Html.Raw(Model.PackageContent)
</div>
</div>
</div>
Controller
using Microsoft.AspNetCore.Mvc;
using StiWebsite.Data;
using StiWebsite.Models;
using System.Dynamic;
namespace StiWebsite.Controllers
{
public class ExperientialController : Controller
{
private ApplicationDbContext _db;
public ExperientialController(ApplicationDbContext db)
{
_db = db;
}
[Route("experiential")]
public IActionResult Experiential()
{
dynamic expModel = new ExpandoObject();
expModel.expL = getExperientialContent();
expModel.studyTourL = getStudyTour();
expModel.tourPackL = getTourPackage();
expModel.countryL = getCountry();
expModel.studyImgPackL = getStudyTourImgPackages();
return View(expModel);
}
//[Route("experiential")]
public PartialViewResult tourPackage(string? id)
{
IEnumerable<StudyTourImgPackage> tourDb = getStudyTourImgPackages();
var detail = tourDb.First(x => x.StudyTourID == id);
return PartialView("tourPackage", detail);
}
public List<StudyTourImgPackage> getStudyTourImgPackages()
{
var expTourList = (from x in _db.TourPackage
select new StudyTourImgPackage
{
PackageID = x.PackageID,
PackageTitle = x.PackageTitle,
PackageContent = x.PackageContent,
PackageIcon = x.PackageIcon,
PackageIconAltText = x.PackageIconAltText,
StudyTourID = x.StudyTourID,
StudyTourTitle = x.StudyTour.StudyTourTitle,
StudyTourContent = x.StudyTour.StudyTourContent,
StudyTourImg = x.StudyTour.StudyTourImg,
StudyTourImgAltText = x.StudyTour.StudyTourImgAltText,
CountryID = x.StudyTour.CountryID,
CountryName = x.StudyTour.Country.CountryName
}).ToList();
return expTourList;
}
}
}

Related

Razor Communicate Display of Modal from PageModel's OnPost() Method

I want to communicate from my Razor PageModel's OnPost() method to display the modal upon validation errors for it. Which basically means changing the modal's css from display none to block. Is there a way for this to be done?
Currently on return Page() the modal is hidden because thats what its css is initially set to, and is normally displayed on the user clicking the button to show it. I marked in my PageModel code where Id like the communication to occur
#page
#{
ViewData["Folder"] = "CourtUser";
<form asp-action="AddorEditUsersOnHearing" method="post" name="AddorEditUsersOnHearingForm" id="AddorEditUsersOnHearing">
<div class="container">
<div class="row">
<div class="col-md-8 mb-4">
<p>Add/Edit Users on <b style="font-style:italic">#Model.HearingName </b></p>
<div class="modal" tabindex="-1" role="dialog" id="AddUserForm">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add User</h5>
<button type="button" onclick="closeAddUserForm()" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group" style="margin-top:5px;padding-left:45px">
<label asp-for="AddUserInput" style="width:100px"></label>
<input asp-for="AddUserInput" class="form-control col-4" id="EmailInputBox" style="display:inline-block" onchange="ValidateEmail()" />
<span style="display:block" asp-validation-for="AddUserInput" class="text-danger"></span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" style="margin:0 auto" asp-page-handler="AddUser" name="AddUserSubmit" value="Yes">Submit</button>
</div>
</div>
</div>
</div>
<input asp-for="HearingId" type="hidden" />
<input asp-for="HearingName" type="hidden" />
<button type="button" class="btn btn-primary" onclick="ShowAddUserForm()">Add User</button>
<button style="float:right" class="btn btn-primary">Remove User(s)</button>
</div>
</div>
</div>
</form>
}
<script type="text/javascript">
function ShowAddUserForm() {
document.getElementById("AddUserForm").style.display = "block";
}
function closeAddUserForm() {
document.getElementById("AddUserForm").style.display = "none";
}
</script>
public IActionResult OnPostAddUser()
{
if (ModelState.IsValid)
{
if (AddUserInput == null)
{
ModelState.AddModelError("AddUserInput", "Please enter an email");
UsersonHearingList = HttpContext.Session.GetObjectFromJson<List<UsersModel>>("UsersonHearingList");
//*****This is where I want to communicate to the view to display the modal.*******
return Page();
}
}
else
{
return RedirectToPage("/Shared/Error");
}
}
You can try to use TempData.Here is a demo:
js:
#section Scripts
{
<script type="text/javascript">
$(function () {
if ("#TempData["Modal"]" == "Display")
{
ShowAddUserForm();
}
});
function ShowAddUserForm() {
document.getElementById("AddUserForm").style.display = "block";
}
function closeAddUserForm() {
document.getElementById("AddUserForm").style.display = "none";
}
</script>
}
handler:
public IActionResult OnPostAddUser()
{
if (ModelState.IsValid)
{
if (AddUserInput == null)
{
ModelState.AddModelError("AddUserInput", "Please enter an email");
UsersonHearingList = HttpContext.Session.GetObjectFromJson<List<UsersModel>>("UsersonHearingList");
//*****This is where I want to communicate to the view to display the modal.*******
TempData["Modal"] = "Display";
return Page();
}
}
else
{
return RedirectToPage("/Shared/Error");
}
}
result:

JavaScript + Bootstrap Dropdown list not allowing me to select the item

I have this bootstrap layout, which is a container inside an accordion-item. There is a dropdown button, containing messages and there's another button that opens a modal to insert a new message and display it in the dropdown list, using localStorage.
When the page loads or is refreshed, I can select the dropdown item normally, but when I add the item, it actually shows up in the list, but I can't select it nor any other item and the selected item is kept there, until the page is reloaded again.
I can still add more messages using the modal and they will still show up in the list.
There's no error in the console to guide me.
The JavaScript code is located at the bottom of the code.
Demonstrating video: https://www.youtube.com/watch?hd=1&v=fhNfpOaJbGs
HTML:
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="ddMensagens" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Selecione Mensagem
</button>
<div class="dropdown-menu scrollable-menu" id="mensagem" aria-labelledby="ddMensagens">
</div>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#staticBackdrop" title="Clique para cadastrar uma nova mensagem">
Cadastrar Nova Mensagem
</button>
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="false" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered"">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalMensagem">Nova Mensagem</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label for="txtMensagem">Digite sua mensagem</label>
<input type="text" class="form-control" id="txtMensagem" placeholder="Mensagem" style="width: 400px">
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="saveMensagem" onclick="addItem();" data-bs-dismiss="modal">Salvar</button>
</div>
</div>
</div>
</div>
</div>
<br />
</div>
</div>
JavaScript:
<script defer>
function updateSelect() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = '';
oldMessage.forEach(element => {
select.innerHTML += `<button class='dropdown-item' type='button'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelect();
text.value = ''
}
}
}
updateSelect()
</script>
LINKS:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Had to change in order to solve my issue (which I still don't know):
function getMensagem() {
let valueMensagem = document.getElementById('mensagem').value;
if (valueMensagem != 0) {
$('select option:selected').each(function (e) {
$('#ContentPlaceHolder1_ddMensagensCopy').val(valueMensagem);
});
}
else {
$('#ContentPlaceHolder1_ddMensagensCopy').val('');
}
}
function updateSelectMensagem() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = "<option value='0'> Selecione uma mensagem </option>";
oldMessage.forEach(element => {
select.innerHTML += `<option class='dropdown-item'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItemMensagem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelectMensagem();
text.value = ''
}
}
}
updateSelectMensagem()
<div class="col-4">
<div class="dropdown-boleto">
<select id="mensagem" class="btn btn-secondary select">
<option value="0">Selecione uma mensagem</option>
</select>
</div>
</div>
.select option {
background: white;
color: #212529;
}
In fact, everything works as expected
https://codesandbox.io/s/shy-cookies-1xt96?file=/index.html

Increasing space between rows in table dynamically created from js function

I have a JS function in a modal that is creating a table in a grid from data being returned from a controller action. It works fine, however I wish there was a little more space between the rows. I have tried adding &nbsp and it doesn't seem to do the trick.
Can anyone give me a solution to this? Below is a picture of the modal, my JS function and the markup for the modal.
modal:
JS function:
$("button[name='paramsBtn']").click(function () {
/* Grabs ID from col selected */
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
var nameType = $col.data('name');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId, "name" : nameType},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var name = [];
var value = [];
var arr = results;
//loop through arr created from dictionary to grab key(s) and value(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
//name += key;
//value += results[key];
name.push(key);
value.push(results[key])
//Remove previous rows
$("div[name='params']").remove();
for (var i in name) {
//Adding parameters as rows
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>'+ '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
}
}
}
}
});
});
markup for modal:
<div class="modal fade" id="paramsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary" style="margin-bottom:-16px;">
<a class="btn btn-xs btn-primary pull-right" data-dismiss="modal" aria-label="Close"><span class="glyphicon glyphicon-remove"></span></a>
<h4 class="modal-title" id="modalTitleText">Job Parameters</h4>
</div>
<div class="modal-body" style="height:250px;">
<div class="list-group">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="width:inherit; margin-bottom:0px;" id="modalGridHeader">
<div class="col-md-6 font-weight-bold"> Parameter(s): </div>
<div class="col-md-6 font-weight-bold"> Value(s): </div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The line that is adding the rows is:
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>'+ '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
Here is where I have tried adding &nbsp. I have also tried adding margin-bottom:5px, but it looked very odd.
Thanks
Quick and dirty
In <div class="col-md-6 text-break" name="params"> add style="height:20px;".

Bootstrap Modal and Badges

I have the following lines of code in my webpage - example/demo.
HTML:
<p data-toggle="modal" data-target="#messagesModal">Messages <span class="badge">2</span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
<div class="alert fade in">
×
<strong>Message 01</strong>:
<p>Lipsum Ipsum
</p>
</div>
<div class="alert fade in">
×
<strong>Message 02</strong>:
<p>Ipsum Lipsum</p>
</div>
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
How can I update the badge to represent the correct amount of messages in the modal?
For example, when the user closes or removes a message in the modal, the badge will go from displaying the number 2 to 1?
Also, is it possible to display the text "There are no more messages." when all of the messages have been removed?
Try this:
//Find message number initially, before editing
$(".badge").text($(".alert").length);
//when the modal is closed
$('#messagesModal').on('hidden.bs.modal', function () {
//Set .badge text equal to the length of the .alert array, i.e the number of messages
$(".badge").text($(".alert").length);
//If there are no '.alert' divs, i.e. no messages
if ($(".alert").length == 0) {
$(".badge").text("No messages");
}
});
This takes all the .alert elements (messages) into an array, and sees how long that array is (i.e. how many messages there are).
Then, it updates .badge to reflect that number.
Working JSFiddle: http://jsfiddle.net/joe_young/62hbqmtp/
Well... I've spend some time, but all that you should do for now:
populate message array with your actual data;
add some actual AJAX for removing messages.
So...
$(function() {
var informer = $("#messageInformer a");
var refreshBadge = function(messageCount) {
var badge = informer.find(".badge");
if (messageCount > 0) {
if (!badge.length) {
informer.text("Messages ");
informer.append("<span class=\"badge\">" + messageCount + "</span>");
} else {
badge.text(messageCount);
}
} else {
informer.text("No messages");
}
};
var buildMessage = function(message) {
var htmlMessage = "<div class=\"alert fade in\">";
htmlMessage += "×";
htmlMessage += "<strong>" + message.title + "</strong>:";
htmlMessage += "<p>" + message.text + "</p>";
return htmlMessage;
}
// There should be real data
var messages = [
{ id: "1", title: "Message 01", text: "Lipsum Ipsum" },
{ id: "2", title: "Message 02", text: "Ipsum Lipsum" }];
refreshBadge(messages.length);
informer.on("click", function(e) {
e.preventDefault();
var modalBody = $(".modal-body");
modalBody.empty();
for (var i = 0; i < messages.length; i++) {
modalBody.append(buildMessage(messages[i]));
}
});
$("body").delegate(".alert .close", "click", function() {
var messageId = $(this).data("id");
// There should be some AJAX possibly
messages = messages.filter(function(el) {
return el.id != messageId;
});
if (messages.length == 0) {
$("#messagesModal").modal("hide");
}
refreshBadge(messages.length);
});
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<p data-toggle="modal" data-target="#messagesModal" id="messageInformer">Messages <span class="badge"></span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>

Cannot link back to MVC view via javascript

I have an Index View and when I click the Edit button, I post to the Edit View (via the Controller) and display a bootstrap modal popup.
By posting to the Edit View, the Controller/View automatically handle getting and displaying the correct data on the modal popup.
Once I'm on my Edit View with the dialog box appearing and I click on the Close button, I simply want to link back to the Index page again; but instead, am getting an error with the path of the url. The new path I want to link to is being "tacked on" to the original path instead of replacing it.
I'm using the Url.Action method inside the click event of the Close button (of which I verified it's hitting) and have verified the location.href url is exactly what is in the url variable as you see in the code.
What do I need to do to correctly link back to the Index url?
Index View
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>Edit
Edit Controller
// GET: Categories/Edit/5
public async Task<ActionResult> Edit(short id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await db.GetCategoryIDAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
Edit View
#model YeagerTechDB.Models.Category
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal" id="categoryEditModal" tabindex="-1" role="dialog" aria-labelledby="categoryModal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="categoryModal-label">Category Description</h4>
</div>
<div class="modal-body">
<div class="form-group">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoryDescription, new { #class = "control-label required col-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3" })
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
#Html.EditorFor(model => model.CategoryDescription, new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.CategoryDescription, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="btnCloseCategory">Close</button>
<button type="submit" class="btn btn-primary" id="btnSaveCategory">Save</button>
</div>
</div>
</div>
</div>
<div>
#Html.Hidden("categoryEditUrl", Url.Action("Edit", "Category", new { area = "Categories" }))
#Html.Hidden("catID", Model.CategoryID)
</div>
#section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentEditCategory == "function")
contentEditCategory()
});
</script>
}
JS for Edit View
$('#btnCloseCategory').click(function (e)
{
var url = '#Url.Action("Index", "Category", new { area = "Categories" })';
location.href = url;
return false;
});
Image of modal popup
Image of error
Assuming your javascript is in an external file you could do the following:
Attach the url to your button within your view with a data attribute as follows:
<button type="submit" class="btn btn-default" id="btnCloseCategory"
data-url="#Url.Action("Index", "Category", new { area = "Categories" })">Close</button>
Then pull back the url with the data method as follows:
$('#btnCloseCategory').click(function (e)
{
var url = $(this).data('url');
location.href = url;
return false;
});
Try changing type="submit" to type="button" for your Close button.
<button type="button" class="btn btn-default" id="btnCloseCategory">Close</button>

Categories