MVC IPageList Paging showing two pager control - asp.net-mvc

I am new to MVC. I am trying to create a Grid structure based on some filters on page and then apply paging. Everything works fine except that when I click on second page, another pager control is added to page resulting in total two pager control on page. Any help would be highly appreciated. Below is my code:
Model:
public class UnMatched
{
public List<string> List_BUnit { get; set; }
public PagedList<UnMatched> List_Grid { get; set; }
}
Controller:
public ActionResult Index(int? page)
{
return Request.IsAjaxRequest()
? (ActionResult)PartialView("AjaxMethod")
: View(PopulateBUnit());
}
public ActionResult AjaxMethod(string bunit, int? Page)
{
//Get lst_UnMatch here
return PartialView(List_Grid.ToPagedList(pageIndex, pageSize));
}
Main View:
#model MVC_Sample.Models.UnMatched
#using PagedList;
#using PagedList.Mvc;
#{
ViewBag.Title = "Home Page";
}
<head>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<div id="GridContainer" style="display:none;">
#Html.Partial("AjaxMethod", Model.List_Grid)
</div>
PartialView:
#model IPagedList<MVC_Sample.Models.UnMatched>
#using PagedList;
#using PagedList.Mvc;
<div id="GridDiv">
<table class="Grid">
<tr>
<th>
#Html.DisplayName("rec_FSRPT_ID")
</th>
<th>
#Html.DisplayName("BUNit")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.rec_FSRPT_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.BUNit)
</td>
</tr>
}
</table>
</div>
</div>
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action("AjaxMethod", new { page = page}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions(){
HttpMethod = "GET", UpdateTargetId = "GridDiv" }))
</div>
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#myPager').html(result);
}
});
return false;
});
});
</script>
Pager Control screenshot:

Instead of #myPager link click use the following code.
<div class="row">
<div class="col col-xs-12 col-sm-6">
<div class="dataTables_info" id="dt_basic_info" role="status" aria-live="polite">Showing <span class="txt-color-darken">#Model.FirstItemOnPage</span> to <span class="txt-color-darken">#Model.LastItemOnPage</span> of <span class="text-primary">#Model.TotalItemCount</span> entries</div>
</div>
<div class="col col-xs-12 col-sm-6">
<a id="pagingFormAction" href="#Url.Action("AjaxMethod", new { Pageindex = 1 bunit = ViewBag.bunit })" style="display:none"></a>
#Html.PagedListPager(Model, page => Url.Action("AjaxMethod", new { Pageindex = page, bunit = ViewBag.bunit }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions() { ContainerDivClasses = new[] { "dataTables_paginate paging_simple_numbers" } }, new AjaxOptions() { HttpMethod = "replace", UpdateTargetId = "GridDiv", OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" }))
</div>
</div>
you can remove OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" if not required.

Thanks all for your help.
I put mypager div inside div Griddiv and it worked. On pager click, i was getting whole grid data again and then binding it to div #GridDiv.
<div id="GridDiv">
// grid.GetHTML code here
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action("AjaxMethod", new { page = page}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions(){
HttpMethod = "GET", UpdateTargetId = "GridDiv" }))
</div>
</div>

Related

Date Fields losing dates when paging MVC

I have an MVC view with a fromDate and a toDate along with a bootstrap datepicker.
The date fields display initally like '15 June 2017'
However, when I do a search, page 1 displays correctly but when i go to any other page the dates reset and show as '06 January 2000'.
Any help would be most appreciated.
Thank you.
Controller:
using PagedList;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication5.Models;
namespace WebApplication5.Controllers
{
public class testController : Controller
{
private JobSubmissionEntities1 db = new JobSubmissionEntities1();
public ViewResult Index(string currentFilter, string searchString, DateTime? fromDate, DateTime? toDate, int? page)
{
if (!fromDate.HasValue) fromDate = DateTime.Now.Date.AddDays(-1);
if (!toDate.HasValue) toDate = DateTime.Now.AddDays(5);
if (toDate < fromDate) toDate = DateTime.Now.AddDays(5);
ViewBag.fromDate = fromDate;
ViewBag.toDate = toDate;
//IF searchString is Empty
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter; fromDate = ViewBag.fromDate; toDate = ViewBag.toDate;
}
ViewBag.CurrentFilter = searchString;
var JobDetails = from s in db.JobDetails
select s;
//if searchString IS NOT empty
if (!String.IsNullOrEmpty(searchString))
{
JobDetails = JobDetails.Where(s =>
(s.JobNo.Equals(searchString) &&
s.SubmissionDate >= fromDate && s.SubmissionDate < toDate));
}
else
{
JobDetails = JobDetails.Where(s => (
s.SubmissionDate >= fromDate && s.SubmissionDate < toDate));
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(JobDetails.OrderBy(i => i.JobNo).ToPagedList(pageNumber, pageSize));
}
}
}
View:
#model PagedList.IPagedList<WebApplication5.Models.JobDetail>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
Layout = "~/Views/Shared/_Layout_Wide.cshtml";
}
ViewBag.Title = "Index";
}
#section DatePicker {
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/moment-with-locales.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
}
<h2>Index</h2>
#{
var fromDate = (DateTime)ViewBag.fromDate;
var toDate = (DateTime)ViewBag.toDate;
}
#using (Html.BeginForm("Index", "Test", FormMethod.Get))
{
/***FromDate***/
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='fromDate'>
<div>#Html.TextBox("fromDate", string.Format("{0:dd MMM yyy}", fromDate), new { #class = "form-control", } )</div>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
/***toDate***/
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='toDate'>
<div>#Html.TextBox("toDate", string.Format("{0:dd MMM yyy}", toDate), new { #class = "form-control", } )</div>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
/***searchString***/
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
#Html.Editor("SearchString", ViewBag.CurrentFilter as string, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
</div>
/***Submit***/
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Search" />
</div>
</div>
</div>
</div>
<hr />
}
<table class="table-bordered">
<tr style="background-color:black">
<th>
#Html.ActionLink("Job No", "Index", new { style = "color:white" })
</th>
<th>
#Html.ActionLink("Submission Date", "Index", null, new { style = "color:white" })
</th>
<th>
#Html.ActionLink("Job Title", "Index", null, new { style = "color:white" })
</th>
<th>
#Html.ActionLink("Article", "Index", null, new { style = "color:white" })
</th>
<th>
#Html.ActionLink("Status", "Index", null, new { style = "color:white" })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
//Highlight Rows Green, Yellow or Red Dependant on Status - Yellow means job has not finished processing
string statusCheck = (item.Status);
string style = "";
if (statusCheck.Contains("Status message 0003:Job finished"))
{
style = "background-color:#e6fff2";
}
else if (statusCheck.Equals("0"))
{
style = "background-color:#ffffcc";
}
else
{
style = "background-color:#ff8080";
}
<tr style="#style">
<td>
#Html.DisplayFor(modelItem => item.JobNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.SubmissionDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.JobDesc)
</td>
<td>
#Html.DisplayFor(modelItem => item.Article)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.SubmissionID }) |
#Html.ActionLink("Details", "Details", new { id = item.SubmissionID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.SubmissionID })
</td>
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, fromDate = ViewBag.fromDate, toDate = toDate }))
#section scripts{
<script type="text/javascript">
$(function () {
$('#fromDate').datetimepicker({
format: 'DD MMMM YYYY',
});
});
</script>
<script type="text/javascript">
$(function () {
$('#toDate').datetimepicker({
format: 'DD MMMM YYYY'
});
});
</script>
}
#Html.TextBox() can pull values out of the ModelState or ViewData.
so you can bind the date values to your text box manually
Kindly refer this link:https://stackoverflow.com/a/29369965/3397630 for an accepted solution which is similar to your problem.
Hope it will be helpful
thanks
Karthik

PagedListPager page always null

This used to work... but now the >> anchor tag of the PagedListPager always passes null to the controller for the page value required...
VS 2013 Web Express & MVC 4 with latest package updates for all.
Just like in Scot Allen's MVC 4 intro, I have a partial view with a PagedListPager
The Controller:
public ActionResult Catalog(string Id= "0", int page=1)
{
var CurrentItemsPage = (get-data-blaw-blaw-blaw).ToPagedList(page,18);
var model = new ShowRoomCatalogPackage(){ CurrentItems = CurrentItemsPage};
return View(model);
}
The catalog page
#model craftstore.Models.ShowRoomCatalogPackage
#{
ViewBag.Title = "Catalog";
Layout = "~/Views/Shared/_Details.cshtml";
}
#using (Ajax.BeginForm("Catalog", "Home", new { category = #Model.SelectedCategoryId, page = 1 },
new AjaxOptions
{
UpdateTargetId = "products",
InsertionMode = InsertionMode.Replace,
HttpMethod = "post"
}
)
)
{
<div class="container" >
<div class="row">
<div class="col-lg-10 col-md-5 col-sm-4 dropdown-menu">
#Html.LabelFor(m => m.SelectedCategoryId)
#Html.DropDownList("id", Model.CategoryItems, new { #id = "ddlCategories", onchange = "this.form.submit();" })
</div>
<div class="col-lg-2 col-md-2 col-sm-1">
#Html.ActionLink("Your Cart", "Index", "ShoppingCart", "", new { #class = "btn btn-green btn-lg" })
</div>
</div>
<div class="row">
#Html.Partial("_CatalogPartial", Model.CurrentItems)
</div><!-- row -->
</div><!-- container -->
}
<br />
<br />
#section Scripts
{
<script type="text/javascript">
new AnimOnScroll(document.getElementById('grid'), {
minDuration: 0.4,
maxDuration: 0.7,
viewportFactor: 0.2
});
</script>
}
The partial view:
#model IPagedList<ShowroomCatalog>
<div id="productList">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="pagedList" data-cs-target="#productList">
#Html.PagedListPager(Model, page => Url.Action("Index", new { category = ViewBag.SelectedCategoryId, page }), PagedListRenderOptions.MinimalWithItemCountText)
</div>
<ul class="grid effect-2" id="grid">
#foreach(var item in Model)
{
var path = String.Format("~/Content/Images/catalog/{0}/{1}", item.OfferType, item.ImagePath);
<li>
<div class="itembox">
<div class="imagebox">
<a href="#Url.Action("Detail", "Home", new { id = item.Id })" title="Detail for #item.CatalogName">
<img class="catalogimg" src="#Url.Content(path)" />
</a>
</div>
<p>#item.CatalogName</p>
</div>
</li>
}
</ul>
</div>
</div><!-- productlist -->
Now the rendered partialview in the browser doesn't have anything in the anchors which may or may not be normal...
<div class="pagedList" data-cs-target="#productList">
<div class="pagination-container"><ul class="pagination"><li class="disabled PagedList-skipToPrevious"><a rel="prev">«</a></li><li class="disabled PagedList-pageCountAndLocation"><a>Showing items 1 through 18 of 65.</a></li><li class="PagedList-skipToNext">»</li></ul></div>
</div>
And when you hover on the >> it doesn't show the page parameter in the URL:
Again, back in the Controller - I get the category (15) but no page parameter or Request.URL parameter is passed to the controller - it's not hiding because of some routing mistake...I think...
How do I get the paging control to work again...???
[EDIT: one more note - the url path on the pager is /controller/action/category/page rather than what shows up on Scot Allen's OdeToFood example where it's equivalent would be /controller/action/category?page=n (like /Home/Catalog/15?page=1 ]
I was missing the JS for the PagedList class anchor element.
var getPage = function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
data: $("form").serialize(),
type: "get"
};
$.ajax(options).done(function (data) {
var target = $a.parents("div.pagedList").attr("data-otf-target");
$(target).replaceWith(data);
});
return false;
};
And this is fired off by :
$(".main-content").on("click", ".pagedList a", getPage);
BUT, this means you need to have your #RenderBody() call in your _Layout.cshtml file wrapped in something with a class of main-content. An example:
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>

Partial View MVC 4 in foreach loop

I'm using MVC 4 Ajax.BeginForm to update but it updates only the first element <div>
the View:
#model List<CSP1225.Models.Item>
#{
ViewBag.Title = "RecentItems";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/CSS/jobs.css" rel="stylesheet" />
#{ var convert = ViewBag.convert;
}
<div>
#foreach (var item in Model)
{
<div class="job-item">
<div class="inner">
<div class="span8 job-span">
<!--start of job list container div-->
<div id="ja-joblist">
<ol id="ja-searchjoblist">
<li class="job-item">#{ var PriceLE = #item.Price * convert;}
#using (#Ajax.BeginForm("_AddToCart", "Home", item, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "cart" }, null))
{
<!-- job item right section-->
<div class="inner">
<div class="ja-job-meta clearfix">
<span class="ja-job-category">#item.ItemName</span>
<span class="ja-job-category">#item.Price $</span>
<span class="ja-job-category">#PriceLE LE</span>
<div id="cart"></div>
<button type="submit">Add to Cart</button>
</div>
</div>
} </li>
<!-- end of job item right section-->
<!-- end of job item -->
</ol>
</div>
</div>
</div>
</div>
}
#Html.ActionLink("Go Back", "Index", "Home", new { #class = "makeneworder" })
</div>
and Controller:
public ActionResult _AddToCart(Item model)
{
ItemModel it = new ItemModel();
it.itemName = model.ItemName;
it.itemUrl = model.ItemURL;
it.quantity = 1;
it.unitprice = model.Price;
it.weight = (int)model.Weight;
it.ItemCategory =(int)model.CategoryID;
CartList.Add(it);
ViewBag.convert = (decimal)_db.Currencies.Where(x => x.Name == "Dollar").FirstOrDefault().Value;
ViewBag.list = CartList;
return PartialView();
}
Partial view :
<p>Added to Cart</p>
but the view returns multiple elements (as long as the list contains elements) when i click Add to Cart it updates the first element.. i understand that because u can not give another <div> the same id but how can i fix it?
you can create a dynamic ID like
#{ var divID = 1; }
then use it like
UpdateTargetId = "cart" + divID }
and
<div id="cart#divID" ></div>

Model properties null on Ajax post from list box change event

I have a view which contains a list box. when users click on an item in the list box I have to post to a controller action method to see the value of the items selected/de-selected in the list box.
So it is posting to the controller action but the model is posted as null. When I post to the controller, I do serialize the form.
In other pages of my application when I serialize the form and post to the controller, the model is never null. I am not sure whats going on in this page but here is the code.
JS File
var serviceEntryURL = '#Url.Action("ServiceSystemSelection", "ServiceEntry")';
$('#systemlstbox').change(function () {
// alert('x');
var overlay = $('<div>loading errorcodes and parts..</div>').prependTo('body').attr('id', 'overlay');
$.post(serviceEntryURL,
$("#form").serialize(),
function (data) {
// $("#runDatestreeview").remove();
// $("#testExceptiontreeview").remove();
// $("#treeview").remove();
// $("#main").html(data);
// $("#ErrorCodeDisplay").empty();
}, "html");
overlay.remove();
});
View
#model RunLog.Domain.Entities.ServiceEntry
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm(new { id = "form", enctype = "multipart/form-data" }))
{
<fieldset>
<legend>Enter a new Service Log Entry</legend>
<h3>
</h3>
#Html.ValidationSummary(true)
<div class="exception">#(ViewBag.ErrorMessage)</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Service Request Number")
</span><span class="rightContent">[Generated] </span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Service Request Date / Time")
</span><span class="rightContent">
#Html.EditorFor(model => model.ServiceDateTime)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Technician")
</span><span class="rightContent">
#Html.DropDownList("TechnicianID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("System")
</span><span class="rightContent">
#Html.ListBoxFor(model => model.SelectedSystemIDs, new
MultiSelectList(ViewBag.SystemID, "Text", "Value",
Model.SelectedSystemIDs), new { id = "systemlstbox", name = "listbox" })
</span>
</div>
}
Controller Action
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ServiceSystemSelection(ServiceEntry serviceEntry)
{
}
I fixed it, the form serialization line was wrong.
$('#systemlstbox').change(function () {
// alert('x');
$.post(serviceEntryURL,
$('form').serialize(),
function (data) {
}, "html");
});

JQuery dialogs don't work after ajax partial view reload

I am manipulating a table of data in a View. When the user clicks on the data name, a dialog pops up to allow him to edit the data. When he clicks, delete, a dialog prompts him to make sure, then deletes the row. When he chooses to create new row, a dialog pops up to allow him to enter the new information. In all 3 cases, after the action is complete, the PartialView "_Content" reloads the content <div />.
This all works fine the first time, after the entire page loads. But after the PartialView reloads (after one of the actions), the "Edit" dialog no longer works, though the other 2 do. I can rig the page to reload everything after each action, of course, but that's slower and doesn't make sense in an Ajax world. If I put the JQueryUIHelper for the edit dialog in the partial view, again, it works the first time, but the second time, the form opens up inline on the page rather than in a dialog. I also tried this using JQuery and JQueryUI directly and got the same error. I have been researching this and experimenting for days.
UPDATED 4/1/13:* I added some $.click() callbacks to the link classes. They don't work after the page does the partial refresh. I guess what's happening is that the scripts lose their "connection" to the objects in the content <div> when the content reloads.
I am using MVC4, Razor, and JQueryUI via the JQueryUIHelper extension. The code for the View and PartialView is below.
Are there any ideas??
Here's my View
#model IEnumerable<AttributeLookup>
#{
ViewBag.Title = "Attributes";
}
<h2>
Attributes</h2>
#if (ViewBag.Error != null)
{
<div class="message-error">#ViewBag.Error</div>
}
<div id="content">
#Html.Partial("_Content", Model)
</div>
<div style="padding-top: 12px;">
#Ajax.ActionLink("New", "Create", new { }, new AjaxOptions {
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "createContent"
}, new { id = "createLink" })
</div>
#using (Html.JQueryUI().Begin(new Dialog()
.Title("Confirm Delete")
.AutoOpen(false)
.Modal(true)
.CloseOnEscape(true)
.ConfirmAjax(".deleteLink", "Yes", "No",
new AjaxSettings { Method = HttpVerbs.Post, Success = "content" })))
{
<div>
Are you sure you want to delete this attribute?
</div>
}
#using (Html.JQueryUI().Begin(new Dialog()
.Title("Create Attribute")
.AutoOpen(false)
.Width(500)
.TriggerClick("#createLink")
.Modal(true)
.CloseOnEscape(true)
.Button("OK", "save")
.Button("Cancel", "closeDialog")))
{
<div id="createContent" />
}
#using (Html.JQueryUI().Begin(new Dialog(new {id = "editDialog"})
.Title("Edit Attribute")
.AutoOpen(false)
.Width(500)
.TriggerClick(".editLink")
.Modal(true)
.CloseOnEscape(true)
.Button("OK", "save")
.Button("Cancel", "closeDialog")))
{
<div id="editContent" />
}
#section Scripts {
<script type="text/javascript">
var success = function(data) {
$(window.document.body).html(data);
};
var content = function(data) {
$("#content").html(data);
};
var closeDialog = function() {
$(this).dialog('close');
};
var saveCreate = function() {
$("#createForm").submit();
$(this).dialog('close');
};
var saveEdit = function() {
$("#editForm").submit();
$(this).dialog('close');
};
$(".editLink").click(function () { alert("edit clicked"); });
$(".deleteLink").click(function () { alert("delete clicked"); });
</script>
}
Here's the PartialView
#model IEnumerable<AttributeLookup>
#if (ViewBag.Error != null)
{
<div class="message-error">#ViewBag.Error</div>
}
<table id="attribute">
<tbody>
<tr>
<th style="width: 250px;">
#Html.DisplayNameFor(model => model.Name)
</th>
<th style="width: 50px;">
#Html.DisplayNameFor(model => model.Units)
</th>
<th style="width: 30px;">
Contrained
</th>
<th style="width: 400px;">
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
 
</th>
</tr>
#{ int count = 0; }
#foreach (var item in Model)
{
string type = count % 2 == 0 ? "normal" : "alt";
<tr class="#type">
<td>
#Ajax.ActionLink(#Html.DisplayFor(modelItem => item.Name).ToHtmlString(), "Edit",
new { id = item.AttributeLookupID }, new AjaxOptions
{
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "editContent"
}, new { #class = "editLink", title = "Edit attribute" })
</td>
<td>
#Html.DisplayFor(modelItem => item.Units)
</td>
<td>
#if (item.AttributeConstraints != null && item.AttributeConstraints.Any())
{
#Html.Raw("X")
}
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id = item.AttributeLookupID }, new { #class = "deleteLink" })
</td>
</tr>
count++;
}
</tbody>
</table>
Here's the Partial for the Edit form. The Create form is similar:
#model AttributeLookup
#using (Ajax.BeginForm("Edit", "AttributeLookup", new AjaxOptions {
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "content"
}, new {id = "editForm"}))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>AttributeLookup</legend>
#Html.HiddenFor(model => model.AttributeLookupID)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Units)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Units)
#Html.ValidationMessageFor(model => model.Units)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AttributeConstraints, "Constraint")
</div>
<div class="editor-field">
#Html.DropDownList("ConstraintTypeID")
#Html.DropDownList("SecondaryID")
</div>
</fieldset>
}
I found a solution. First, I removed the TriggerClick from the Helper:
#using (Html.JQueryUI().Begin(new Dialog(new {#id = "editDialog"})
.Title("Edit Attribute")
.AutoOpen(false)
.Width(500)
// deleted --> .TriggerClick(".editLink")
.Modal(true)
.CloseOnEscape(true)
.Button("OK", "saveEdit")
.Button("Cancel", "closeDialog")))
{
<div id="editContent" />
}
And then I explicitly added it to my <scripts>:
$("body").on('click', ".editLink", function () { $("#editDialog").dialog("open"); });
Now it works fine.
I wonder why it works for the other two, but not the edit one? I suspect it has to to with mistakes startingfrom the id. Try taking away id=editdialog. This might be a quickfix. If this doesnt work, keep reading.
The #dialog usually hides due to jqueryUi things that go on at document.ready or page load in the background.
I'm not sure exaclty when it happens, but you'd want to repeat those steps after the reload happens.
At the end of the document in a part thats not reloaded do something like...
<script>
$("body").ajaxComplete( reHideDialog())
function reHideDialog(){
$("#dialog").css('display','none');
}
</script>
when they click the edit link, jqueryui should automatically set the #dialog css display to display:absolute as it renders it in a popup.

Resources