ASP.NET MVC code modal popup not sending parameter to controller - asp.net-mvc

I am trying to present Organization Details in a partial view in a Bootstrap Modal. After a day of reading/watching tutorials I am stumped.
Organizations are loaded into a Table and there is a View option on each row. The table has an id="OrganizationGrid"
<table class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0" id="OrganizationGrid">
<thead>
<tr style="color:#126E75; background-color:lightcyan">
<th style=" width:5%">
#Html.ActionLink("ID", "Index", new { sortOrder = ViewBag.IDSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th style=" width:25%">
#Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter })
</th>
<th style=" width:25%">
Parent Org
</th>
<th style=" width:10%; text-align:center">
Website
</th>
<th style="width:25%">
Comment
</th>
<th scope="col" colspan="3" style=" width:10%; text-align:center">Action</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr class=" table-light">
<td style="text-align:left">
#Html.DisplayFor(modelItem => item.Id)
</td>
<td style="text-align:left">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td style="text-align:left">
#Html.DisplayFor(modelItem => item.ParentOrg.Name)
</td>
<td style="text-align: center">
<a href=#Html.DisplayFor(modelItem=> item.Website) target="_blank">
<i class="fa-solid fa-globe" target="_blank" rel="noopener noreferrer"></i>
</a>
</td>
<td style="text-align:left">
#Html.DisplayFor(modelItem => item.Comment)
</td>
<td style="text-align: center">
<a asp-action="Edit" asp-route-id="#item.Id">
<i class="fas fa-edit"></i>
</a>
</td>
<td>
<a class="details" href="javascript:;">View</a>
</td>
<td style="text-align: center">
<a asp-action="Delete" asp-route-id="#item.Id">
<i class="fas fa-trash" style="color:red"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
My understanding is that it triggers the JavaScript function which is currently residing at the bottom of the same page:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#OrganizationGrid .details").click(function() {
var organizationId = $(this).closest("tr").find("td").eq(0).html();
$.ajax({
type: "POST",
url: "/Organizations/Details",
data: '{organizationId: "' + organizationId + '" }',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function(response) {
$("#partialModal").find(".modal-body").html(response);
$("#partialModal").modal('show');
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
});
});
</script>
I inserted a break in the controller to see if ajax was passing the organizationId but it is not. This is the Controller Details Action method:
[HttpPost]
public ActionResult Details(int organizationId)
{
var organization = _context.Organizations
.Include(o => o.ParentOrg).Where(p=>p.Id == organizationId);
if (organization == null)
{
return NotFound();
}
return PartialView("_Details", organization);
}
If I hard code organizationId in the Controller the popup loads with the correct information BUT if I hard code organizationId in the JavaScript function it still passes a null value to the controller. Could someone please point me in the right direction.

The issue was with the JavaScript function and specifically the syntax of the data attribute in ajax. Corrected solution is as follows:
$(function () {
$("#OrganizationGrid .details").click(function () {
var organizationId = $(this).closest("tr").find("td").eq(0).html();
//alert(organizationId)
$.ajax({
type: "POST",
url: "/Organizations/Details",
data: { 'id': organizationId },
//contentType: "application/json; charset=utf-8",
//dataType: "html",
success: function (response) {
$("#viewEditOrgModal").find(".modal-body").html(response);
$("#viewEditOrgModal").modal('show');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});

Related

MVC Partial Page returns whole page, not just the partial

I have a button on a page:
<div>
From:
<input id="fromDate" type="date" name="fromDate" value="#a.FromDate">
To:
<input id="toDate" type="date" value="#a.ToDate">
<button type="button" id="btn_transactions" class="btn btn-primary" onclick="btnTrans()"><span class="glyphicon glyphicon-search"></span></button>
<label class="buy-heading">Total Buys: #String.Format("{0:n0}", #q.BuyQuantity)</label><label class="sell-heading">Total Sells: #String.Format("{0:n0}", #q.SellQuantity)</label>
</div>
It calls this function on click:
function btnTrans() {
var postdata = { "symbol": $("#savesymbol").val(), "fromDate": $("#fromDate").val(), toDate: $("#toDate").val() };
var url = "Company/Transactions?symbol=" + $("#savesymbol").val() + "&fromDate=" + $("#fromDate").val() + "&toDate=" + $("#toDate").val();
$.ajax({
url: url,
success: function (result) {
alert(result)
$('#transTarget').html(result);
},
error: function () {
//alert("Error occured");
}
});
}
The controller method is:
public async Task<PartialViewResult> Transactions(string symbol, string
fromDate, string toDate)
{
return PartialView("Transactions");
}
This is the partial view:
<table id="transactionsTable" class="table table-bordered display hover no-wrap dataTables" style="width: 100%">
<thead>
<tr>
<th>Account Category</th>
<th>Trade Date</th>
<th>Account Name</th>
<th>Activity</th>
<th>Quantity</th>
<th>Exec Price</th>
<th>Principal</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
var a = item.accounts;
foreach (var item2 in a)
{
<tr>
<td>#item2.AcctCategory</td>
<td>#String.Format("{0:MM/dd/yyyy}", #item2.TradeDate)</td>
<td>#item2.AccountName</td>
<td>#item2.Trans</td>
<td>#String.Format("{0:n}", item2.Quantity)</td>
<td>#String.Format("{0:n}", item2.ExecutionPrice)</td>
<td>#String.Format("{0:n}", item2.PrincipalAmount)</td>
</tr>
}
}
</tbody>
</table>
I have 3 partials on this page as follows:
<div class="mycontent2">
#{Html.RenderAction("Documents", "Company");}
</div>
<div class="mycontent2">
#{Html.RenderAction("Holdings", "Company");}
</div>
<div class="mycontent2">
#{Html.RenderAction("Transactions", "Company");}
</div>
The problem is that the partial view returned from the controller method returns the WHOLE page, not just the partial part of transactions. What am I doing wrong?
Return a model from the controller. Like this;
return PartialView("Transactions", model);
Do it for others partial.
Then, you will use model in your view.
Use #{ Layout = null; } in your partial view.

Partial View Not Rendering inside div

So I was trying to follow this guide and the followup article.
But Before I started with the searching, sorting and filtering, I wanted to see if even the pages were working as intended.
Unfortunately they are not and I cant for the life of me figure it out why, I even went so far as to download his working example just to see if it was something with my browser. (To download his working example its at the top of the second article, I cant post more then 2 links)
Since his worked I compared his views, controllers and scripts side by side to mine and from what I can tell they mirror each other.
So I ended up copying my code somewhere else and pasted his into my project, changed the ActionLinks to reflect the naming conventions I used and left out the stuff I havent implemented yet (noted above). And it still do sent work.
When I run them side by side I get no errors in the console, they are loading the same scripts with the exception that I added jquery.unobstrusive-ajax.js as an attempt to correct it from searching for solutions, but it didnt help.
I have no idea what I'm doing wrong here :/
My Manage View - Correlates to his Home Index View
The only thing I really changed here is the action link
#{
ViewBag.Title = "Home Page";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/ModalDialog.js"></script>
<style>
.testClass {
font-size: xx-large;
text-transform: capitalize;
}
</style>
<title>
Complete example of MVC pagination, filtering and sortig inside patial view with edit in modal dialog
</title>
</head>
<body style="padding-top:0">
<table style="width:100%;" border="1" cellspacing="0" cellpadding="0">
<tr>
<td style="" colspan="2">
<div id="logo" style="height:70px; background-color:rgba(86, 111, 111, 1);font: 1.5em Georgia, Times New Roman, Times, serif;">
Complete example of MVC pagination, filtering and sortig inside patial view with edit in modal dialog
</div>
<div id="navigation" style="background-color:#a4c2c2">
HOME
</div>
</td>
</tr>
<tr style="height:600px">
<td style="width:200px;background-color: #a4c2c2; vertical-align:top; padding-top:10px; padding-left:10px">
<div>
<ul>
<li>
#Html.ActionLink("Manage Assets", "MasterDetail", "Assets", new { }, new { id = "btnCustomers", #class = "btn btn-default btn-xs" })
</li>
</ul>
</div>
</td>
<td>
<div id="contentFrame" style="width:100%; height:600px; padding-top:10px; padding-left:10px" />
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(function () {
$.ajaxSetup({cache : false})
$('#btnCustomers').click(function () {
$('#contentFrame').mask("waiting ...");
$('#contentFrame').load(this.href, function (response, status, xhr) {
$('#contentFrame').unmask("waiting ...");
});
return false;
});
});
</script>
My MasterDetail View - Correlates to his Customers Index view
My table is setup different because i havent done everything he has yet
#using PagedList.Mvc
#model PagedList.IPagedList<Furst_Alpha_2._0.Models.Quantities>
#{
Layout = null;
}
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/ModalDialog.js"></script>
<h2>Inventory Management</h2>
<p>
#Html.ActionLink("Create New", "_Create", new { id = -1 }, new { btnName = "btnCreate", #class = "btn btn-default btn-xs" })
</p>
<table class="table">
<tr>
<th>
Category
</th>
<th>
Make
</th>
<th>
Model
</th>
<th>
Type
</th>
<th>
Length
</th>
<th>
Width
</th>
<th>
Height
</th>
<th>
Weight
</th>
<th>
Description
</th>
<th>
Rental Price
</th>
<th>
Number Of Techs
</th>
<th>
Total
</th>
<th>
In User
</th>
<th>
Availability
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Assets.Category.CategoryName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Make.MakeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Model.ModelName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Type.TypeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Length)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Width)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Height)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Weight)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.RentalPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.NumTechsReq)
</td>
<td>
#Html.DisplayFor(modelItem => item.total)
</td>
<td>
#Html.DisplayFor(modelItem => item.InUse)
</td>
<td>
#Html.DisplayFor(modelItem => item.Availability)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.QuantityId }, new { btnName = "btnEdit", #class = "btn btn-default btn-xs" })
#Html.ActionLink("Delete", "Delete", new { id = item.QuantityId }, new { btnName = "btnDelete", #class = "btn btn-default btn-xs" })
</td>
</tr>
}
</table>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
<div id="myPager">
#Html.PagedListPager(Model, page => Url.Action("MasterDetail", new { page, OrderID = ViewBag.OrderID }))
</div>
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
setDialogLink($('a[btnName=btnCreate]'), 'Add New Asset', 500, 600, "contentFrame", "/Assets/MasterDetail");
setDialogLink($('a[btnName=btnEdit]'), 'Edit Customer', 500, 600, "contentFrame", "/Customers/Index");
setDialogLink($('a[btnName=btnDetails]'), 'Customer Details', 500, 600, "contentFrame", "/Customers/Index");
$('a[btnName=btnDelete]').click(function (e) {
e.preventDefault();
var confirmResult = confirm("Are you sure?");
if (confirmResult)
{
$('#contentFrame').mask("waiting ...");
$.ajax(
{
url: this.href,
type: 'POST',
data: JSON.stringify({}),
dataType: 'json',
traditional: true,
contentType: "application/json; charset=utf-8",
success:function(data)
{
if (data.success) {
$('#contentFrame').load("/Customers/Index");
}
else {
alert(data.errormessage);
}
$('#contentFrame').unmask("waiting ...");
},
error: function (data) {
alert("An error has occured!!!");
$('#contentFrame').unmask("waiting ...");
}
});
}
})
$("a[btnName=FilterCustomer]").click(function (e) {
e.preventDefault();
var search = $('input[name=search]').val();
this.href = this.href.replace('xyz', search);
$('#contentFrame').mask("waiting ...");
$.ajax({
url: this.href,
type: 'POST',
cache: false,
success: function (result) {
$('#contentFrame').unmask("waiting ...");
$('#contentFrame').html(result);
}
});
});
$(".SortButton").click(function (e) {
e.preventDefault();
$('#contentFrame').mask("waiting ...");
$.ajax({
url: this.href,
type: 'POST',
cache: false,
success: function (result) {
$('#contentFrame').unmask("waiting ...");
$('#contentFrame').html(result);
}
})
});
$('#myPager').on('click', 'a', function (e) {
e.preventDefault();
$('#contentFrame').mask("waiting ...");
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#contentFrame').unmask("waiting ...");
$('#contentFrame').html(result);
}
});
});
});
</script>
My AssetsController Manage and MasterDetail methods which correlate to his HomeController Index and CustomerController Index methods respectively.
// GET: Assets
public ActionResult Manage()
{
return View();
}
// GET: MasterDetail
public ActionResult MasterDetail(int? page)
{
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());
//ApplicationUser user = db.Users.First(u => u.Id == userr.Id);
var assets = db.Quantities.Where(a => a.VendorId == user.VendorId).OrderByDescending(a => a.AssetId);
int pageNumber = page ?? 1;
int pageSize = 3;
return PartialView(assets.ToPagedList(pageNumber, pageSize));
}
I am not too sure about what your problem is, but I THINK there I saw a problem in your code.
in MasterDetail.cshtml try replacing
#Html.PagedListPager(Model, page => Url.Action("_MasterDetail", new { page, OrderID = ViewBag.OrderID }))
with
#Html.PagedListPager(Model, page => Url.Action("MasterDetail", new { page, OrderID = ViewBag.OrderID }))
Url.Action expects an Action name, not a razor view name.
So last night while laying in bed stumped as to whats causing the problem I thought well maybe I should just look up alternatives. I saw some Ajax variations (that youll see commented out) and I ended up on this SO thread which ultimately lead me to a solution.
Below is the end result of my tinkering, I left commented code in from my attempts so you'll see other thigns I've tried. Other than this all I changed in the view was add a reference for a modal wait screen and then changed Html.ActionLink to a button. <input id="btnCustomers" type="button" value="Manage Assets" />
<script type="text/javascript">
$(function () {
$.ajaxSetup({cache : false})
$('#btnCustomers').click(function () {
//$('#contentFrame').mask("waiting ...");
waitingDialog.show("Please wait while we prepare your inventory ...");
$('#contentFrame').load('#Url.Action("MasterDetail","Assets")', function () {
setTimeout(function () {
waitingDialog.hide();
}, 1000);
});
//$.ajax({
// type: 'GET',
// url: '#Url.Content("~/Assets/MasterDetail")',
// data: -1,
// success: function (data) {
// $('#contentFrame').innerHtml = waitingDialog.hide();
//$('#contentFrame').load('#Url.Action("MasterDetail","Assets")');
// }
//})
//$('#contentFrame').load(this.href, function (response, status, xhr) {
// $('#contentFrame').unmask("waiting ...");
//});
return false;
});
});
</script>

jquery tabs not working inside dialog as partial view

I am opening a dialog with the following:
This is my Appliation Details.cshmtl
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$(".display tr:odd").addClass("odd");
$(".display tr:even").addClass("even");
//modal popup
$("#dialog-confirm").dialog({
autoOpen: false,
resizable: false,
height: 200,
width: 400,
modal: true,
buttons: {
"Delete": function () {
$(this).dialog("close");
$('#deleteApplication').submit();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$(".deleteLink").click(function (e) {
e.preventDefault();
$("#dialog-confirm").dialog("open");
});
$(".openDialog").live("click", function (e) {
e.preventDefault();
$("<div></div>")
.addClass("dialog")
.attr("id", $(this).attr("data-dialog-id"))
.appendTo("body")
.dialog({
title: $(this).attr("data-dialog-title"),
close: function () { $(this).remove() },
modal: true,
width: "90%",
height: "500",
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
})
.load(this.href);
});
$(".close").live("click", function (e) {
e.preventDefault();
$(this).closest(".dialog").dialog("close");
});
});
</script>
<div class="tabset">
<ul class="tab_labels">
<li><span>Details</span></li>
<li><span>Versions</span></li>
<li><span>History</span></li>
<li><span>Log</span></li>
</ul>
<div class="tab_content">
<table id="detailsView" class="display">
<tbody>
<tr>
<td>#Html.LabelFor(model => model.ApplicationName)</td>
<td>#Html.DisplayFor(model => model.ApplicationName)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Description)</td>
<td>#Html.DisplayFor(model => model.Description)</td>
</tr>
</tbody>
</table>
</div>
<div class="tab_content">
#Html.Partial("_Versions", versions, new ViewDataDictionary {{ "applicationId", Model.ApplicationId}})
</div>
<div class="tab_content">
#Html.Partial("_RecordHistory", history)
</div>
<div class="tab_content">
#Html.Partial("_RecordLog", log)
</div>
</div>
<br />
<div class="button_wrapper_center">
<span style="white-space:nowrap;">Return to List</span>
</div>
<div id="dialog-confirm" title="Delete the item?" style="display:none" >
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be deleted. Are you sure?</p>
</div>
The partial view _Versions contains the link to open the dialog
This is _Versions.cshtml
#model IEnumerable<WebDevelopment.SqlData.Version>
#{
var applicationId = ViewData["applicationId"];
}
<script type="text/javascript">
$(document).ready(function () {
var recordId;
$(".deleteVersionLink").click(function (e) {
e.preventDefault();
var frm = $(this);
recordId = frm.attr("id");
$("#dialog-confirmVersion").dialog("open");
});
$("#dialog-confirmVersion").dialog({
autoOpen: false,
resizable: false,
height: 200,
width: 400,
modal: true,
buttons: {
"Delete": function () {
$("#deleteVersion" + recordId).submit();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#versions').dataTable({
"bFilter": false,
"bPaginate": false,
"bInfo": false,
"bSort": false
});
});
</script>
<table>
<tr>
<td>
<span style="white-space:nowrap;">Create New</span>
</td>
</tr>
</table>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="versions">
<thead>
<tr>
<th>
#Html.LabelFor(p => Model.FirstOrDefault().VersionNumber)
</th>
<th>
#Html.LabelFor(p => Model.FirstOrDefault().ReleaseDate)
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(item.VersionNumber, "Details", "Version", new { id = item.VersionId }, new { #class = "openDialog", data_dialog_id = "detailsDialog", data_dialog_title = "Version Details" })
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Version", new { id = item.VersionId }, null) |
#Html.ActionLink("Delete", "DeleteConfirmed", "Version", new { id = item.VersionId }, new { #class = "deleteVersionLink", #id = item.VersionId })
#using (Html.BeginForm("DeleteConfirmed", "Version", new { id = item.VersionId }, FormMethod.Post, new { #id = "deleteVersion" + item.VersionId })){}
</td>
</tr>
}
</tbody>
</table>
<div id="dialog-confirmVersion" title="Delete the item?" style="display:none" >
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be deleted. Are you sure?</p>
</div>
Here is the Version Contoller
public ActionResult Details(int id)
{
ViewBag.History = recordHistoryRepository.GetRecordHistory("ConnectionString", "Version", id);
ViewBag.Log = recordLogRepository.GetRecordLog("ConnectionString", "Version", id);
var version = versionRepository.GetVersionById(id);
if (Request.IsAjaxRequest())
{
return PartialView("_DetailsDialog", version);
}
return View(version);
}
Here is Version Details.cshtml
#model WebDevelopment.SqlData.Version
#Html.Partial("_DetailsDialog")
Here is _DetailsDialog
#model WebDevelopment.SqlData.Version
#{
var history = ViewBag.History as IEnumerable<WebDevelopment.SqlData.RecordHistory>;
var log = ViewBag.Log as IEnumerable<WebDevelopment.SqlData.RecordLog>;
}
<table width="100%">
<tr>
<td><h1 class="first">#Html.DisplayTextFor(_ => Model.Application.ApplicationName)</h1></td>
</tr>
</table>
<div class="tabset">
<ul class="tab_labels">
<li><span>Details</span></li>
<li><span>History</span></li>
<li><span>Log</span></li>
</ul>
<div class="tab_content">
<table id="detailsDialogView" class="display">
<tbody>
<tr>
<td>#Html.LabelFor(model => model.VersionNumber)</td>
<td>#Html.DisplayFor(model => model.VersionNumber)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.ReleaseDate)</td>
<td>#Html.DisplayFor(model => model.ReleaseDate)</td>
</tr>
</tbody>
</table>
</div>
<div class="tab_content">
#Html.Partial("_RecordHistory", history)
</div>
<div class="tab_content">
#Html.Partial("_RecordLog", log)
</div>
</div>
The dialog opens and I see the html for the _DetailsDialog page in firebug, but the tabs are not functioning. The datatables in partial views _RecordHistory and _RecordLog from _DetailsDialog.cshtml do not function as well.
I had a similar problem - and did not find a solution. I went to the easytabs plugin instead (http://os.alfajango.com/easytabs/). It works like a charm and I find easy to use and adapt.

MVC multiple forms on single view not working

I have 2 forms on a single razor view that open in seperate dialog boxes. The forms are submitted using jquery post..
First form works perfectly but the second form isnt recognised at all and when I try to serializr the data it returns an empty string.
Code below:
#using (Html.BeginForm("SaveElectricReading", "Store", FormMethod.Post, new { id = "frmSaveElectricReading" }))
{
<div id="electricDialog" style="display: none;" title="Electric Readings">
<p>
Please ensure the electric readings have been entered!
</p>
<table width="100%">
<tr>
<th>
Serial:
</th>
</tr>
<tr>
<td>
<input type="text" name="Serial" />
</td>
</tr>
<tr>
<th>
Reading:
</th>
</tr>
<tr>
<td>
<input type="text" name="Reading" />
</td>
</tr>
<tr>
<th>
Comment:
</th>
</tr>
<tr>
<td>
<div class="textwrapper">
<textarea rows="5" cols="10" name="Comment"></textarea>
</div>
</td>
</tr>
</table>
</div>
}
#using (Html.BeginForm("SaveWaterReading", "Store", FormMethod.Post, new { id = "myform" }))
{
<div id="waterDialog" style="display: none;" title="Water Readings">
<p>
Please ensure the water readings have been entered!
</p>
<table width="100%">
<tr>
<th>
Serial:
</th>
</tr>
<tr>
<td>
<input type="text" name="WaterSerial" />
</td>
</tr>
<tr>
<th>
Reading:
</th>
</tr>
<tr>
<td>
<input type="text" name="WaterReadingsdfsdf" />
</td>
</tr>
<tr>
<th>
Comment:
</th>
</tr>
<tr>
<td>
<div class="textwrapper">
<textarea rows="5" cols="10" name="WaterComment"></textarea>
</div>
</td>
</tr>
</table>
</div>
}
function showWaterDialog() {
var $dialog = $('#waterDialog').dialog({
autoOpen: false,
modal: true,
width: 400,
height: 400,
buttons: {
Submit: function () {
// $('#frmCreateStore').submit();
var data = $('#frmSaveWaterReading');
$.post("/Store/SaveWaterReading",
$("#frmSaveWaterReading").serialize(),
function () {
$("#waterDialog").dialog("close");
});
//$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$dialog.dialog('open');
}
In the jquery function for showing the dialog with the form in it, I needed to add that dialog content to the second form on the page as follows:
$("#waterDialog").parent().appendTo($("form").eq(1)[0]);

ASP MVC 3: LoadingElementId element only shows on first request

I have the following problem. I am using an AjaxForm in ASP MVC 3 and the LoadingElementId works fine only in the first request, it is not shown on the next ones. Why can this be happening?
View:
#model ICollection<Indirect_eSod.ViewModels.OrderSearchViewModel>
#using Indirect_eSod.Helpers
#{
ViewBag.Title = "Sales Order Lookup";
}
<script type="text/javascript">
$(document).ready(function () {
$("#id").keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
});
</script>
#using ( Ajax.BeginForm(new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "results",
LoadingElementId = "ajaxSplash",
InsertionMode = InsertionMode.Replace
}))
{
<div id="Criteria" style="width: 800px;margin-left:10%">
<table id="tblSearchCriteria" class="FunnyRedLine" width="100%">
<tr class="SODRow">
<td class="SODLabel">
eSod ID:
</td>
<td colspan="4">
#Html.TextBox("id", null, new { #class = "Text"})
</td>
<td style="width: 40%"></td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Start Date:
</td>
<td>
#Html.TextBox("startDate", null, new { #class = "Text", #readonly="readonly" })
#Ajax.Calendar("startDate")
</td>
<td class="SODSpacer75px">
</td>
<td class="SODLabel">
End Date:
</td>
<td>
#Html.TextBox("endDate", null, new { #class = "Text", #readonly = "readonly" })
#Ajax.Calendar("endDate")
</td>
<td style="width: 40%"></td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Post Code:
</td>
<td colspan="4">
#Html.TextBox("postCode", null, new { #class = "Text" })
</td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Sales Person:
</td>
<td colspan="4">
#Html.DropDownList("salesPersonId", new SelectList(ViewBag.SalesPeople, "UserId", "FullName"), String.Empty, new { #class = "Text" })
</td>
<td style="width: 40%">
</td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Sales Person Ref:
</td>
<td colspan="4">
#Html.TextBox("salesPersonRef", null, new { #class = "Text" })
</td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Order Type:
</td>
<td colspan="4">
#Html.DropDownList("orderTypeId", new SelectList(ViewBag.OrderTypes, "SodTypeID", "SodTypeDesc"), String.Empty, new { #class = "Text" })
</td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Serial No:
</td>
<td colspan="4">
#Html.TextBox("serialNo", null, new { #class = "Text" })
</td>
</tr>
<tr class="SODRow">
<td class="SODLabel">
Customer PO:
</td>
<td colspan="4">
#Html.TextBox("customerPO", null, new { #class = "Text" })
</td>
<td style="width: 40%">
<input id="btnSearch" type="submit" value="Search" class="Text" />
#Html.Hidden("hdnNoCache",#DateTime.Now)
</td>
</tr>
</table>
</div>
}
<div id="results" />
#Html.Partial("AjaxSplash")
The AjaxSplash Source
<div id="ajaxSplash" style="display:none;z-index:60;" class="transparent">
<table id="Table1" width="100%" style="height: 100%; text-align: center">
<tr align="center">
<td align="center" valign="middle">
<img alt="" src="/Content/Images/ajax-loader2.gif" id="img2" />
</td>
</tr>
<tr align="center">
<td align="center" style="font-family: Verdana; font-size: 8pt; font-weight: bold;
color: Navy;">
Please Wait..
</td>
</tr>
</table>
</div>
The Controller
[Ajax(true)]
[CacheControl(HttpCacheability.NoCache),HttpGet]
public ActionResult Index(string id, string startDate, string endDate, string postCode, string salesPersonId, string salesPersonRef,
string orderTypeId, string serialNo, string customerPO)
{
var service = new eSodSrv();
var viewModel = service.GetHeaders(id.ToInt32(), salesPersonId.ToInt32(), orderTypeId.ToInt32(), startDate.ToDate(), endDate.ToDate(), postCode, customerPO, serialNo, salesPersonRef);
return PartialView("SearchResults",viewModel);
}
EDIT
I think I've tracked what the problem is. After the AJAX call when I make a document.getElementById('ajaxSplash') I get null. I still have no idea why this is happening though
I actually prefer not to do it this way and instead in my layout define a div and attach
$('#waitImageDiv')
.hide()
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
ANY ajax events will automatically show this image then automatically.
OK I found the solution, it seems that LoadingElementId will only work if the div is inside the AJAX Form, otherwise the div will end up as a null after the first call.
It looks like the loading element div must be the first element in the ajax form for the feature to work properly.
Try the following:
#using ( Ajax.BeginForm(new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "results",
LoadingElementId = "ajaxSplash",
InsertionMode = InsertionMode.Replace
}))
{
#Html.Partial("AjaxSplash")
....

Resources