MVC 4 Using Paged List in a partial View - asp.net-mvc

I am trying to implement PagedList in a partial view.
Describing the view setup. I have Controller A with ViewA. This is the parent view and has its own model. Then I have Controller B with PartialViewB and has its own model as well. Then I have a Div in ViewA that will be used to display the PartialViewB. I can load in PartialViewB after hitting a button and then hide the view after hitting the button again. Within the PartialViewB is the PagedList. Hitting the next page button loads the next page, but loads it in its own page, not in the ViewA as it was before.
I can load up more code as needed, but for now here is the Pager
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewComments",
new { courseID = #ViewBag.courseID, page }),
new PagedListRenderOptions { MaximumPageNumbersToDisplay = 5, DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded })
::EDIT::
Parent View
<div class="Comments">
<input type="button" id="View" class="CommentsButton" value="View Comments"/>
<input type="hidden" id="Hidden" value="false" />
</div>
<div id="Comments">
</div>
PartialView
#model PagedList.IPagedList<QIEducationWebApp.Models.CourseComment>
#using PagedList.Mvc;
#{
ViewBag.Title = "Comments";
}
<h2>Comments!</h2>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CommentDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.CommentText)
</td>
</tr>
}
</table>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewComments",
new { courseID = #ViewBag.courseID, page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new PagedListRenderOptions { MaximumPageNumbersToDisplay = 5, DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded },
new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "Comments" }))
BundleConfig.cs
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css", "~/Content/PagedList.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}

Check this out: Related SO question
This will use unobtrusive ajax to do the replace for you. You just need to handle the fetch and skip on your end and send back the new partial view along with the model.
#Html.PagedListPager(Model, page => Url.Action("ViewComments", page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing( new AjaxOptions(){ HttpMethod = "GET", UpdateTargetId = "partialContainerYouNeedToReplace"}))
Make sure that you have unobtrusive js referenced on your page when doing this. It comes with MVC out of the box and you should just need to reference the bundle.
Hope this helps.

Related

MVC IPageList Paging showing two pager control

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>

Display partial view in a view using mvc 4

I want to display a partial view inside a main view upon clicking view link, within the same page. Help me please, I am newbie in MVC. Is there any other way to do it other than using the Ajax.ActionLink()?
This is my Add Detail controller.
public ActionResult DisplayDetails()
{
SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
connect.Open();
DataSet ds = ExecuteQuery("select EmployeeID, EmployeeName, EmailID from EmployeeDetails");
IList<AddDetails> lst = new List<AddDetails>();
AddDetails ad;
foreach (DataRow dr in ds.Tables[0].Rows)
{
ad = new AddDetails();
ad.EmployeeId = Convert.ToInt32(dr["EmployeeID"]);
ad.EmployeeName = dr["EmployeeName"].ToString();
ad.EmailId = dr["EmailID"].ToString();
lst.Add(ad);
}
connect.Close();
return PartialView("DisplayDetails", lst);
}
Here is the main view
AddDetail view(main view).
#model mvcEmployeeTask.Models.AddDetails
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("AddDetail", "AddDetails", FormMethod.Post))
{
<table>
#* <tr>
<td>
#(Html.Label("Employee ID : "))
</td>
<td>
#Html.TextBoxFor(model => model.EmployeeId)
#Html.HiddenFor(model => model.EmployeeId)
</td>
</tr>*#
#Html.HiddenFor(model => model.EmployeeId)
<tr>
<td>
#(Html.Label("Employee Name : "))
</td>
<td>
#(Html.TextBoxFor(model => model.EmployeeName))
</td>
</tr>
<tr>
<td>
#(Html.Label("Email ID : "))
</td>
<td>
#(Html.TextBoxFor(model => model.EmailId))
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit" name="Add" />
</td>
<td>
#* #Html.ActionLink("View", "DisplayDetails")*#
#Html.ActionLink("View", "DisplayDetails")
</td>
</tr>
</table>
#Html.Action("DisplayDetails", "AddDetails");
}
Here is the partial view (Display view).
#model IList<mvcEmployeeTask.Models.AddDetails>
#{
Layout = null;
}
#using (Html.BeginForm("DisplayDetails", "AddDetails", FormMethod.Get))
{
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DisplayDetails</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body> <div class="table" align="center">
<table border="1" >
<tr>
<th>EmployeeID</th>
<th>EmployeeName</th>
<th>Email</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#item.EmployeeId
</td>
<td>
#item.EmployeeName
</td>
<td>
#item.EmailId
</td>
<td>
#Html.ActionLink("Edit", "EditDetails", new { id= item.EmployeeId })
</td>
<td>
#Html.ActionLink("Delete", "DeleteDetails", new { id= item.EmployeeId })
</td>
</tr>
}
</table>
</div>
</body>
</html>
}
Please Help me!!
You should use
#Ajax.ActionLink
Reason:
Ajax.ActionLink is much like Html.ActionLink counterpart, it also creates the hyperlink Click here but when user clicks it and have the JavaScript enabled browser, Ajax.ActionLink sends the asynchronous request instead of navigating to new URL. With Ajax.ActionLink we specify what controller’s action method to invoke and also specify what to do with the response coming back from the action method and it suits your case really well.
Instead of
#Html.ActionLink("View", "DisplayDetails")
Description:
It will render the partial view on the same index screen instead of opening new window.
Something like this
#Ajax.ActionLink(" ", "ViewDetails", "Auditor", new AjaxOptions { UpdateTargetId = "yourviewDiv"}) //yourviewdiv is id of div where you want to show your partial view onClick
Your Main View
#model mvcEmployeeTask.Models.AddDetails
<div id = "yourviewDiv">
// it will populate your partial view here.
</div>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("AddDetail", "AddDetails", FormMethod.Post))
{
#Ajax.ActionLink(" ", "ViewDetails", "Auditor", new AjaxOptions { UpdateTargetId = "yourviewDiv"})
}
load following div using its id on particular event(say button click of your main view) then partial view will be load on your main view.
<div id="loadpartialview">
#Html.Partial("_yourPartialViewName")
</div>
here is nice tutorial how to implement it:
http://mvc4beginner.com/Tutorial/MVC-Partial-Views.html
The simple version of code is
<div>
#Html.Partial("PartialView1", Model.partialModel)
</div>
Theory:
To have it dynamic you need to create ajax call to render the action on server and insert the result to the page.
the question how to implement this has been already answered here:
MVC Partial view with controller, ajax - how do I ge the partial controller to get data?

Ajax.BeginForm not working with Html.ValidationSummary

I am trying to use the Ajax.BeginForm to post data to a controller. In the case of specific errors, the form should re-render and display the custom error message that was added to the ModelState. For some reason, the error message is not displaying. I am even trying the following test case which is not working, am I missing something?
Edit.cshtml:
#using (Ajax.BeginForm("Edit", "UserInformation", FormMethod.Post, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divFormContainerMain", LoadingElementId = "divPreLoader", OnSuccess = "onSuccess" }))
{
<div id="divPreLoader" style="display:none; text-align: center"><img src="#Url.Content("~/Content/images/preLoader.gif")" alt="" /></div>
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
</div>
<div class="buttonContainerBottom">
<span class="buttonContainerInner">
<input type="submit" id="btnSave" name="buttonPress" value="save" class="orangeButton" />
</span>
</div>
}
_EditPartialView.cshtml:
#Html.ValidationSummary(false)
<div id="divFormContainerUserInformation" class="formContainer">
<div class="labelContainer">
#Html.LabelFor(m => m.UserName)
</div>
<div class="elementContainer">
#Html.TextBoxFor(m => m.UserName, new { style = "width: 200px" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="labelContainer">
#Html.LabelFor(m => m.Name)
</div>
<div class="elementContainer">
#Html.TextBoxFor(m => m.Name, new { style = "width: 200px" })
#Html.ValidationMessageFor(m => m.Name)
</div>
<div class="labelContainer">
#Html.LabelFor(m => m.EmailAddress)
</div>
<div class="elementContainer">
#Html.TextBoxFor(m => m.EmailAddress, new { style = "width: 200px" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
.
.
.
.
.
.
</div>
UserController:
[HttpPost]
public ActionResult Edit(UserModel userModel)
{
ModelState.AddModelError("", "This is a test");
return PartialView("_EditPartialView", userModel);
}
Where are your scripts added? In the _layout.cshtml or in the view itself? How are you loading the view? Is it with an ajax request to show a partial view?
If you are loading the partial view through ajax or as a partial view, maybe it could be that the partial view was not yet loaded in the jquery DOM model tree.
I would try the following. Change
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
</div>
to
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
</div>
or
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
#Scripts.Render("~/bundles/jqueryval") //if you have a bundle for it
</div>
My advice is anyway to load the validate and unobtrusive scripts only when you need them and not in the _layout.cshtml page.
Also don't forget to enable the following appSettings in the web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Make sure that you have included the jquery.unobtrusive-ajax.js script to your view after jquery itself. Otherwise the Ajax.BeginForm helper won't do what you think it does:
<script type="text/javascript" src="#Url.Content("~/scripts/jquery-YOUR-VERSION.js")"></script>
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.unobtrusive-ajax.js")"></script>

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.

script block not include in ajax response

In my application I have a common layout for all the views, from one of the view(Index.cshtml) i have used Ajax.BeginForm to display another view as a response the code for this is
#using (Ajax.BeginForm("Edit", "Home", new AjaxOptions { UpdateTargetId = "content",InsertionMode=InsertionMode.Replace }))
now my problem is as a response the edit view is rendered as expected but the script block with in the edit view is not included and hence the javascript is not executed.
#model Test.Models.CARE
#{
ViewBag.Title = "Edit";
}
<script>
function s() {
alert("hi");
}
</script>
<h2 style="padding: 0px; margin-top: 0px;">
Edit</h2>
#using (Html.BeginForm("SaveForConfirmation", "Home"))
{
Plz help.
It's bad practice to put javascript code in views, let alone partial views. So I would recommend you to externalize this javascript code in a separate function in a separate javascript file.
And then you could subscribe to the OnSuccess event of the Ajax.BeginForm helper:
#using (Ajax.BeginForm("Edit", "Home", new AjaxOptions { OnSuccess = "editSuccess", UpdateTargetId = "content", InsertionMode = InsertionMode.Replace }))
{
...
}
and then define the editSuccess function in a separate javascript file:
function editSuccess(result) {
alert('hi');
}
now in your partial view you should leave only what is supposed to be in a partial - markup. Get rid of any <script> tags, you don't need them. You don't need any inline scripts. They only increase the size of your webpages and waste bandwidth as they cannot be cached by the browsers:;
#model Test.Models.CARE
<h2 style="padding: 0px; margin-top: 0px;">Edit</h2>
#using (Html.BeginForm("SaveForConfirmation", "Home"))
{
...
}
UPDATE:
If you have some poorly written javascript that depends on crap like ViewBag inside the partial then you could invoke the corresponding function from within the OnSuccess callback:
#using (Ajax.BeginForm("Edit", "Home", new AjaxOptions { OnSuccess = "s", UpdateTargetId = "content", InsertionMode = InsertionMode.Replace }))
{
...
}
Notice how I have defined OnSuccess = "s" where s is the function that you have defined in your partial and which will be invoked in this case. But I repeat once again, this is a wrong approach and should only be used if you don't have time to refactor your code properly.
Finally have achieved the required functionality.
this is how I have done it
View (from where the call was made)
<input type="submit" value="Create" />
#using (Ajax.BeginForm("Edit", "Home", new AjaxOptions {OnSuccess="DisableControls()",
InsertionMode= InsertionMode.Replace,UpdateTargetId="DivToUpdate" }))
The Controller
[HttpPost]
public ActionResult Edit(FormCollection fc)
{
if (fc.Keys[0].ToString().TrimEnd() == "Display")
{
TempData["readonly"] = "readonly";
}
else
TempData["readonly"] = "";
The Called Partial view
#model TestApp.Models.CUSTOMER
#{
ViewBag.Title = "Edit";
}
<script>
function s() {
var readonly="#TempData["readonly"].ToString()";
if(readonly=="readonly")
{
$('input[type="text"],select').attr('readonly','readonly');
$("#Save").remove();
}
}
</script>
<h2 style="padding: 0px; margin-top: 0px;">
Edit</h2>
#using (Html.BeginForm("Save", "Home"))
{
#Html.ValidationSummary()
<fieldset>
<legend>CUSTOMER</legend>
<table style="margin: 0px auto;">
<tr>
<td>
Now on diagnosing the cause for the previous failure attempt I wrote a alert() in the script to see whether the script is executing or not.
<script>
function s() {
var readonly="#TempData["readonly"].ToString()";var s="hi"+ prompt("name","");
alert(s);
if(readonly=="readonly")
{ //To make all text boxes and dropdown readonly
$('input[type="text"],select').attr('readonly','readonly');
$("#Save").remove();//To Remove the save button
}
}
</script>
on further looking up with the firebug I could see that the response contains the script
<script>
function s() {
var readonly="readonly";var s="hi"+ prompt("sdfs","kakaji");
alert(s );
if(readonly=="readonly")
{
$('input[type="text"],select').attr('readonly','readonly');
$("#Save").remove();
}
}
</script>
<form action="/Grid/Save" method="post"><div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<fieldset>
<legend>CUSTOMER</legend>
<table style="margin: 0px auto;">
<tr>
<td>
<div class="editor-label">
But what found that the generated page doesn't include the script for which I found a reason here
Hence this solves my problem and gave me a reason behind the fact that WHY I could not see or watch my script tag from the Ajax response.

Resources