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.
Related
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);
}
});
});
});
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>
I'm using MVC Http.BeginForm to create a search form.
Now I want to add create button, which opens Popup, but when I press it HttpPost event in controller fires up. How can I prevent HttpPost event to fire up when popup is pressed?
#using (Html.BeginForm())
{
<table border="0">
<tr>
<td style="padding: 5px;">A:</td>
<td style="padding: 5px;">#Html.TextBox("slicplate", "", new { style="width:120px; height:25px;" })</td>
<td style="padding: 5px;">B:</td>
<td style="padding: 5px;">#Html.TextBox("smodelis", "", new { style="width:120px; height:25px;" })</td>
<td style="padding: 5px;">C:</td>
<td style="padding: 5px;">#Html.TextBox("suzsakovas", "", new { style = "width:120px; height:25px;" })</td>
<td style="padding: 5px;">D:</td>
<td style="padding: 5px;">#Html.TextBox("svairuotojas", "", new { style = "width:120px; height:25px;" })</td>
<td style="padding: 5px;" rowspan="3" valign="top"><input type="submit" value="Search" style="height:59px;" /></td>
<td style="padding: 5px;" rowspan="3">
<button class="btn btn-primary" style="height:50px; width:100px;" ng-click="open('new_tp')">Popup button</button>
</td>
</tr>
</table>
}
Open function:
var ModalDemoCtrl = function ($scope, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function (size, id) {
var modalInstance
if (size == "new_tp") {
modalInstance = $modal.open({
templateUrl: '/Transport/Create',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
}
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
And ModalDemoCtrl function:
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$('.modal-dialog').close;
$modalInstance.close($scope.selected.item);
};
$scope.delete = function (id) {
$('.modal-dialog').close;
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
Change code from
<button class="btn btn-primary" style="height:50px; width:100px;" ng-click="open('new_tp')">Popup button</button>
To:
<button class="btn btn-primary" type="button" style="height:50px; width:100px;" ng-click="open('new_tp')">Popup button</button>
I have an array of JSON objects in the page source that all work except a child object (category).
Here is the code in cshtml:
<script type="text/javascript">
var initialData = #Html.Raw(Json.Encode(ViewBag.OfferItems));
</script>
Here is the resulting page source:
<script type="text/javascript">
var initialData = [{"Id":1,"Name":"Item1","ProductVariantLinks":[{"category":{"Id":2,"Name":"Basic Pizza","Products":null},"product":{"Id":1,"Name":"Margherita","Description":null,"ProductVariants":null},"productVariant":{"Id":1,"Name":"10 inch"}},{"category":{"Id":2,"Name":"Basic Pizza","Products":null},"product":{"Id":2,"Name":"Zeno","Description":null,"ProductVariants":null},"productVariant":{"Id":4,"Name":"8 inch"}}]},{"Id":2,"Name":"Item2","ProductVariantLinks":[]}];
</script>
As far as I can tell category is there and contains properties, but it appears as undefined in IE's debugger.
Is there something I'm missing?
P.S. the JSON is valid.
Update
I'm using knockoutjs and category is in inialdata until it does ko.applybindings. I'm not sure why it would do this, code below:
/// <reference path="jquery-1.5.1.js" />
/// <reference path="knockout-2.0.0.js" />
var ProductVariantLink = function() {
var self = this;
self.category = ko.observable();
self.product = ko.observable();
self.productVariant = ko.observable();
// Whenever the category changes, reset the product selection
self.category.subscribe(function() {
self.product(undefined);
self.productVariant(undefined);
});
};
var OfferItem = function() {
var self = this;
self.Name = new String();
self.ProductVariants = new Array();
};
var SpecialOfferItemModel = function (specialOfferItems) {
var self = this;
self.specialOfferItems = ko.observableArray(ko.utils.arrayMap(specialOfferItems, function (specialOfferItem) {
return { Id: specialOfferItem.Id, Name: specialOfferItem.Name, ProductVariants: ko.observableArray(specialOfferItem.ProductVariantLinks) };
}));
self.addSpecialOfferItem = function () {
self.specialOfferItems.push({
Id: "",
Name: "",
ProductVariants: ko.observableArray()
});
};
self.removeSpecialOfferItem = function (specialOfferItem) {
self.specialOfferItems.remove(specialOfferItem);
};
self.addProductVariant = function (specialOfferItem) {
specialOfferItem.ProductVariants.push(new ProductVariantLink());
};
self.removeProductVariant = function (ProductVariant) {
$.each(self.specialOfferItems(), function () { this.ProductVariants.remove(ProductVariant) })
};
self.save = function () {
var OfferItems = new Array();
$.each(self.specialOfferItems(),
function () {
var item = this;
var offer = new OfferItem();
offer.Name = item.Name;
$.each(item.ProductVariants(),
function () {
offer.ProductVariants.push(this.ProductVariant);
});
OfferItems.push(offer);
});
self.lastSavedJson(JSON.stringify(ko.toJS(self.specialOfferItems()), null, 2));
return false;
};
self.lastSavedJson = ko.observable("");
};
var model = new SpecialOfferItemModel(initialData);
ko.applyBindings(model);
$(function () {
$('#myForm').submit(function () {
model.save();
});
});
<table class="specialOfferItemsEditor">
<tr>
<th>
</th>
<th>
Name
</th>
<th>
ProductVariants
</th>
</tr>
<tbody data-bind="foreach: specialOfferItems">
<tr>
<td>
<div>
Delete</div>
</td>
<td>
<input data-bind="value: Name" />
</td>
<td>
<table>
<tr>
<th>
Category
</th>
<th>
Product
</th>
<th>
ProductVariant
</th>
</tr>
<tbody data-bind="foreach: ProductVariants">
<tr>
<td>
<select data-bind='options: ProductCategories, optionsText: "Name", optionsCaption: "Select...", value: category, uniqueName: true'>
</select>
</td>
<td data-bind="with: category">
<select data-bind='options: Products, optionsText: "Name", optionsCaption: "Select...", value: $parent.product, uniqueName: true' >
</select>
</td>
<td data-bind="with: product">
<select data-bind='options: ProductVariants, optionsText: "Name", optionsCaption: "Select...", value: $parent.ProductVariant, uniqueName: true'
>
</select>
</td>
<td>
<a href='#' data-bind='click: $root.removeProductVariant'>Delete</a>
</td>
</tr>
</tbody>
</table>
<a href='#' data-bind='click: $root.addProductVariant'>Add Product Variant</a>
</td>
</tr>
</tbody>
</table>
The JSON isn't coming in as you're expecting. I assigned the JSON string you provided above and my IE debugger was able to find 'category' without any issues.
Screenshot: https://i.stack.imgur.com/cI60U.jpg
Try to console.log (or alert) JSON.stringify(initialData);
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