Partial View Not Rendering inside div - asp.net-mvc

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>

Related

ASP.NET MVC code modal popup not sending parameter to controller

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);
}
});
});
});

Azure show syntax error in Razor views, but page load in localhost

I have a website application running in windows azure, but, when I do login in application, Azure return error 500 to me.
On the Azure Website Event Viewer extension, have this exception:
Exception type: HttpParseException
Exception message: The if block is missing a closing "}" character.
Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.
Request information:
Request URL: http://independentmusicstore.azurewebsites.net/Music
Request path: /Music
User host address: 177.203.93.129
User: pedro
Is authenticated: True
Authentication Type: Forms
Thread account name: IIS APPPOOL\independentmusicstore
And this is the view after login that the error 500 happens:
#model IEnumerable<TestTcc2.Models.Musica>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutMusico.cshtml";
}
<script src="Content/audiojs/audio.min.js"></script>
<div class="row">
<div class="col-md-4"></div>
<div id="divAudio" class="col-md-4">
<audio id="audioPlay" src="x" preload="auto" onplay="true" />
<script>
audiojs.events.ready(function () {
var as = audiojs.createAll({
autoplay: true,
autoload: "none"
});
});
function replaceAll(str, de, para) {
var pos = str.indexOf(de);
while (pos > -1) {
str = str.replace(de, para);
pos = str.indexOf(de);
}
return (str);
}
function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
var rep = replaceAll(sParameterName[1], "%2F", "/");
rep = replaceAll(rep, "%20", " ");
return rep;
}
}
}
var x = getUrlParameter('path');
$('#audioPlay').attr('src', x);
</script>
</div>
<div class="col-md-4"></div>
</div>
<br />
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table table-hover table-bordered">
<tr>
<th>
<span>Genero</span>
</th>
<th>
<span>Nome</span>
</th>
<th>
<span>Artista</span>
</th>
<th>
<span>Preço</span>
</th>
<th></th>
</tr>
#foreach (var item in Model) {
if (item.UserId == Int32.Parse(Membership.GetUser().ProviderUserKey.ToString()))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.genero.Nome)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nome)
</td>
<td>
#Html.DisplayFor(modelItem => item.NomeArtista)
</td>
<td>
#Html.DisplayFor(modelItem => item.Preco)
</td>
<td>
#Html.ActionLink("Play", "", new { path = item.path }) |
#Html.ActionLink("Edit", "Edit", new { id=item.MusicaId }) |
#Html.ActionLink("Download", "Download", new { path = item.path }) |
#Html.ActionLink("Delete", "Delete", new { id=item.MusicaId })
</td>
</tr>
}
}
</table>
As you can see, don't have any { } incorrect, how can I fix it?
This is the detailed Error that I take in the log from azure
Detailed Error Information:
Module ManagedPipelineHandler
Notification ExecuteRequestHandler
Handler System.Web.Mvc.MvcHandler
Error Code 0x00000000
Requested URL http://independentmusicstore:80/Music
Physical Path D:\home\site\wwwroot\Music
Logon Method Forms
Logon User pedro
I would move the
if (item.UserId == Int32.Parse(Membership.GetUser().ProviderUserKey.ToString()))
{
code to the controller and pass a view model of the authorized data.

jQuery-ui autocomplete causes validation to fail if result is null

Long day and I'm still beating my head against the desk over this one. I think I've read every jQuery ui autocomplete post here on stack overflow as well as most of the jQuery ui documentation.
The Problem:
I have a form in an asp.net mvc 4 application. The form is for submitting a timesheet/work ticket. The user selects a project and based upon that project an autocomplete field for work order number is enabled. If the user chooses and existing work order number for the project, I populate two additional inputs with information about the work order. I need to allow the user to type in a completely new work order with out selecting an autocomplete suggested work order and still have the form validate. The problem is that validation fails if I do not select a suggestion from the autocomplete.
The jQuery-ui documentation does show that the methods close, disable, and destroy available to be used but I'm not finding a good example of how to use them and which would actually be best to use in my situation. Also it might be worth noting that I am using jQuery-ui 1.9
The error I get:
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
The error points to the line of code on my controller where I call _db.SaveChanges();
if ( ModelState.IsValid )
{
_db.WorkTickets.Add(workticket);
_db.SaveChanges();
}
The model state is valid and I have no nulls trying to be saved. My model does allow nulls on a few fields but in this case all fields are complete.
The form works great if I choose an existing work order from the autocomplete widget or if I leave it blank. It only fails if I type in a new work order. I have set a break point and verified that the model does have the value I typed in for work ticket.WONumber before calling save changes.
Here is my jQuery.
$(document).ready(function () {
$("#ProjectID").change(function () {
var id = $(this).val();
var results = "result";
var source1 = "Project/QuickCCSearch?project=" + id;
$("#ChargeCode").autocomplete({ source: source1 });
$("#ChargeCode").attr("disabled", false)
var source2 = "Project/QuickPOSearch?project=" + id;
$("#PONumber").autocomplete({ source: source2 });
$("#PONumber").attr("disabled", false)
var source3 = "Project/QuickWOSearch?project=" + id;
$("#WONumber").attr("disabled", false)
$("#WONumber").autocomplete({
source: function (request, response) {
$.ajax({
url: source3,
data: request,
success: function (data) {
response(data);
if (data.length === 0) {
$("#WONumber").attr("check", false);
}
}
});
},
change: function () {
if ($("#WONumber").attr("check") != false) {
$.getJSON("Project/JobLocation", { wo: $("#WONumber").val() },
function (data) {
$("#JobLocation").val(data);
});
$.getJSON("Project/JobDescription", { wo: $("#WONumber").val() },
function (data) {
$("#JobDescription").val(data);
});
}
}
});
$.getJSON("WorkTicket/GetClient/", { id: id },
function (data) {
$("#Client").html(data);
});
$.getJSON("WorkTicket/GetClientRep/", { id: id },
function (data) {
$("#ClientRep").html(data);
});
$.getJSON("WorkTicket/GetManager/", { id: id },
function (data) {
$("#Manager").html(data);
});
});
})
Edit:
Here is my Html
#model WorkTicket
#{
ViewBag.Title = "Create";
}
<article>
<div class="linearBg1">
Create Daily Work Ticket
</div>
<br />
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<div class="linearBg1">
General Information
</div>
<div class="section-span-body">
<table>
<tr class="empTableRowBody2">
<th class="empTableRowBody2">
#Html.LabelFor(Model => Model.DateWorked)
</th>
<th class="empTableRowBody2" colspan="2">
#Html.LabelFor(Model => Model.ProjectName)
</th>
</tr>
<tr>
<td>
#Html.EditorFor(Model => Model.DateWorked)
</td>
<td colspan="2">
#Html.DropDownList("ProjectID")
</td>
</tr>
<tr class="empTableRowBody2">
<th class="empTableRowBody2">
Client
</th>
<th class="empTableRowBody2">
Client Rep
</th>
<th class="empTableRowBody2">
Manager
</th>
</tr>
<tr>
<td>
<div id="Client"></div>
</td>
<td>
<div id="ClientRep"></div>
</td>
<td>
<div id="Manager"></div>
</td>
</tr>
<tr class="empTableRowBody2">
<th class="empTableRowBody2">
Charge Code
</th>
<th class="empTableRowBody2">
PO Number
</th>
<th class="empTableRowBody2">
Work Order
</th>
</tr>
<tr>
<td>
#Html.TextBoxFor(Model => Model.ChargeCode, new { disabled = true })
</td>
<td>
#Html.TextBoxFor(Model => Model.PONumber, new { disabled = true })
</td>
<td>
#Html.TextBoxFor(Model => Model.WONumber, new { disabled = true, check = true })
</td>
</tr>
<tr class="empTableRowBody2">
<th class="empTableRowBody2" colspan="3">
Job Location
</th>
</tr>
<tr>
<td colspan="3">
#Html.TextBoxFor(Model => Model.JobLocation, new { #class = "inputWidth500" })
</td>
</tr>
<tr class="empTableRowBody2">
<th class="empTableRowBody2" colspan="3">
Job Description
</th>
</tr>
<tr>
<td colspan="3">
#Html.TextBoxFor(Model => Model.JobDescription, new { #class = "inputWidth500" })
</td>
</tr>
</table>
</div>
<div class="section-span-footer"></div>
<br />
<div>
<input type="submit" value="Next" />
</div>
}
</article>
#section Menu{
#Html.Partial("_MainMenu")
#Html.Partial("_MenuFooter")
}
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/WorkTicket.js")
}
I'm sure I'm doing many things wrong as I am new to jQuery and still learning. Is there a way to disable the autocomplete if the user does not choose an option from the autocomplete widget or if the result of the widget is null? Thank you in advance!
T.
Ok, I finally solved it. It has nothing to do with autocomplete. Just goes to show how much I need to learn about jQuery. I had a bad line of code in my controller where I was saving information about the new work order back to the project. I was missing one required item and I was just over looking it. Sorry for being an idiot and ignorant about jQuery. Thanks anyone that looked. Can't believe that took me so long to see.......

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.

Pass filename as parameter to Controller through jQuery

I am trying to upload an image using jQuery-ui dialog and pass the image file to the controller which will actually do the uploading work. However, I can't seem to get it right. The code is given below
View:
<table>
<tr>
<th>
Image
</th>
<th>
Name
</th>
</tr>
#foreach (var item in Model.CourseApplicationForms)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.thumbnail)
</td>
<td>
#Html.DisplayFor(modelItem => item.sname)
</td>
<td>
Upload File
</td>
</tr>
}
</table>
<div id="dialog" title="Upload files">
#using(Html.BeginForm("ImageUpload","Student", FormMethod.Post, new {id="photouploadform", enctype = "multipart/form-data" }))
{
<p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p><br />
<p><input type="submit" value="Upload file" /></p>
<input type="hidden" id="EnrollId" />
}
</div>
<script type="text/javascript">
$(function () {
$('.photoupload').click(function (event) {
$('#EnrollId').val(event.target.id);
$('#dialog').dialog('open');
});
$('#photouploadform').submit(function () {
$.getJSON("/Student/ImageUpload/", {
Id: $('#EnrollId').val(), file: $('#fileUpload')
}, function (data) {
$('#dialog').append('<p>' + data + '</p>');
});
return false;
});
$("#dialog").dialog({
autoOpen: false,
show: "blind",
width: 400,
hide: "fade",
modal: true,
resizable: false
});
});
</script>
Controller
[AcceptVerbs(HttpVerbs.Get)]
JsonResult ImageUpload(int Id, HttpPostedFileBase file = null)
{
string filePath = string.Empty;
if (file.ContentLength > 0)
{
Directory.CreateDirectory(HttpContext.Server.MapPath("~/Content/Photo/medium"));
filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Photo/medium"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
I want to pass the fileupload image but don't have a clue how to do it. Kindly help
Thanks in advance

Resources