I'm trying to prevent the scrolling to the top when using jQuery's .load function. I've read at SO that you can use event.preventDefault(); event.stopPropagation();. Here is the link to this question. But when using beginform, you don't have an event here.
I also tried to put a click event on the submit button, but this also didn't work.
Thanks in advance!
This is the code of the view. When success the function closeFancyReservationCancel is called.
#using (
Ajax.BeginForm("Cancel",
"Reservation",
new AjaxOptions { HttpMethod = "POST",
OnSuccess = "closeFancyReservationCancel"},
new { id = "cancelForm" }))
{
...
}
)
And this is the jQuery function
function closeFancyReservationCancel() {
$.fancybox.close();
$('#reservationList').load(ResolveUrl('~/Reservation/reservationList'));
}
function ResolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url;
}
Here a part of my HTML:
<div id="reservationList" class="tblContainer">
#Html.Action("reservationList", "Reservation")
</div>
The action reservationList returns a view with the table. Only the body of the table has an overflow: auto;.
EDIT: added more information
I have a div with a list of my reservations table. I am using MVC3 to show that list. When press the cancel button, the div will reload by the .load function.
EDIT
Here my HTML view with the table:
Pastebin
You can simply get the Scroll amount before loading. And apply the same scroll amount after load is finished
function closeFancyReservationCancel() {
$.fancybox.close();
var scroll_amount= $('#reservationList').scrollTop();
$('#reservationList').load(ResolveUrl('~/Reservation/reservationList'),
function() {
$('#reservationList').scrollTop(scroll_amount);
});
}
If you want you can also use .scrollLeft() amount.
Related
This is a follow on to similar question but taking suggestions into account.
Render part of page on dropdown selection
I have a chart on my main view which I would like to update partially when a dropdown selects different values.
The page renders correctly the first time, but when I select a new value in the dropdown, then I think the .submit script is failing in the script .submit() because when I put a break on window.submitAjaxForm it is never reached.
_PnlChart.cshtml
<img src="#Url.Action("CreateTraderPnlChart3")" width="600" height="600" align="middle" vspace="50" />
My mainview Index.cshtml:
<div class="w3-half">
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#using (Ajax.BeginForm("GetEnvironment",
new RouteValueDictionary { { "Environment", "" } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" }, new { id = "ajaxForm" } ))
{
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"],
new
{ onchange = "submitAjaxForm()" })
}
</script>
<script type="text/javascript">
$('form#ajaxForm').submit(function(event) {
eval($(this).attr('onsubmit')); return false;
});
window.submitAjaxForm = function(){
$('form#ajaxForm').submit();
}
</script>
</div>
My controller:
public ActionResult PeriodSelection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
{
Session["Period"] = dropdownlistReturnValue;
return PartialView("~/Views/Employee/_PnlChart.cshtml");
}
This line in your code,
eval($(this).attr('onsubmit')); return false;
I am not sure what you were intending to do here. But from your question, i assume you wanted to do a form submission. But that line will not submit the form. The expression $(this).attr('onsubmit') is going to return undefined as your form does not have an onsubmit attribute defined.
But you already have the form submit code in your other method (submitAjaxForm). So if you simply remove the $('form#ajaxForm').submit handler (apparently it does not do anything useful), your code will work. When you change the dropdown, it will make an ajax form submission.
But your form action is set to GetEnvironment action method. That means your ajax form submission will be to that action method. In your question you have a different action method which returns the updated chart content. It does not makes sense!
I personally prefer to write handwritten ajax calls instead of relying on the ajax action helper methods. The below is the code i would probably use (Except the dropdownlist code. read further)
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"], new
{ data_charturl = Url.Action("PeriodSelection","Home")})
Now listen to the change event of the SELECT element.
$(function(){
$("#PeriodSelection").change(function(){
var v = $(this).val();
var url=$(this).data("charturl")+'?dropdownlistReturnValue='+v;
$("#ExportDiv").load(url);
});
});
You should consider using the a view model to pass the Dropdownlist data. Why not use the DropDownListFor helper method ? It looks much clean, Mixing a lot of C# code (See all the session casting and all.) makes it kind of dirty IMHO.
I am trying to do a drill down report. I am using MVC and Devexpress Gridviews. I render my view and the partial view and display my gridview with the result.
Now what I need to accomplished is when I double click on the gridview I need to render a new/different partial view in the place off the existing gridview - The one I double clicked on.
Is this possible?
Here is what I have:
public ActionResult MainPartial()
{
using (var Context = new DataContext())
{
ViewBag.Level = 0;
return PartialView("MainPartial",SomeData);
}
}
public ActionResult FirstDrilldownPartial(int Param)
{
using (var Context = new DataContext())
{
ViewBag.Level = 1;
return PartialView("FirstDrilldownPartial",SomeNewData(Param));
}
}
My Gridview RowDblClick event
function onDoubleClick(s, e) {
$.ajax({
type: 'POST',
url: '/Controler/FirstDrilldownPartial',
dataType: 'json',
async: false,
//cache: false,
data: {
Param: 1
}
});
}
At the moment everything is working but when I call the function "function onDoubleClick(s, e)" the Main grid stay on the view and the new grid is not rendered.
Can someone please help with suggestions.
Thanks
You can render both partials in different divs and hide or show in your js function a div, for example
<div id="mydiv1">
#Html.Partial("Partial1")
<div>
<div id="mydiv2">
#Html.Partial("Partial2")
</div>
and in your onDoubleClick ( I assume that you are using jQuery)
$("#mydiv1").hide();
$("#mydiv2").show();
and to hide (on page load) the second div first just add
$(function () {
$("#mydiv2").hide();
});
or use
<div id="mydiv2" style="display:none;">
This code is not tested, but it should work.
I have a script file scripts.js with a function that styles all checkboxes in page. This file is referenced in the master page.
There is a user control and a aspx test page for it. On page load, the UC shows a list of checkboxes and the style is applied.
On clicking a button, an ajax call gets a list from database and binds some more checkboxes to the page. But for the new checkboxes, the style is not applied. What could be going wrong.
scripts.js:
function selectcheckBtn() {
alert(1);
if ($("input:checkbox").prev("span").length === 0) {
alert(2);
$("<span class='uncheked'></span>").insertBefore("input:checkbox")
}
$("input:checkbox").click(function () {
check = $(this).is(":checked");
if (check) {
$(this).prev("span").addClass("cheked").removeClass("uncheked")
} else {
$(this).prev("span").addClass("uncheked").removeClass("cheked")
}
});
$("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
}
ctrl.ascx:
<script>
function ShowMore() {
$.ajax({
url: "/_layouts/15/handlers/ShowMore.ashx",
data: {},
success: function (msg) {
//append new chkbox list to existing list. It is hidden at first and later faded in.
$(".divList").append(msg);
selectcheckBtn();
$(".hideDiv").fadeIn(300).removeClass("hideDiv");
},
error: function (msg) {
alert("An error occurred while processing your request");
}
});
}
</script>
Show more
On page load both alerts pop. But on clicking 'Show More', only alert(1) pops.
There are no errors in browser console.
Rendered HTML:
//with style applied to chkboxes on page load
<div><span class="uncheked"></span><input type="checkbox" runat="server" id="406">
<label>Compare</label></div>
//with no style applied to new chkboxes
<div><input type="checkbox" runat="server" id="618"><label>Compare</label></div>
I did not understand why the if condition wasn't true in selectcheckBtn();, for the new chkboxes. So, added a new class for the checkboxes and wrote this workaround.
Now calling this function instead of selectcheckBtn(); in the ajax code, worked.
function StyleCheckBox() {
$(".chkBx").each(function () {
if ($(this).prev("span").length === 0) {
$("<span class='uncheked'></span>").insertBefore($(this));
}
$("input:checkbox").click(function () {
check = $(this).is(":checked");
if (check) {
$(this).prev("span").addClass("cheked").removeClass("uncheked")
} else {
$(this).prev("span").addClass("uncheked").removeClass("cheked")
}
});
$("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
});
}
This is a problem I haven't come across before.
I'm working on an MVC4 project. I'm using an asp button control because there isn't a Html Helper that can be used for a button (re: There's no #Html.Button !). My button code is:
<td><asp:Button ID="ButtonUndo" runat="server" Text="Undo"
OnClick="ButtonUndo_Click" AutoPostBack="true"/></td>
I went to the Designer tab and clicked on this button which produced the event handler:
protected void ButtonUndo_Click(object sender, EventArgs e)
{
RRSPSqlEntities db = new RRSPSqlEntities();
int id = (int)ViewData["ClientId"];
var updateAddress = (from a in db.Address
where a.PersonId == id
select a).SingleOrDefault();
updateAddress.Deleted = false;
db.SaveChanges();
}
I should add that this code was added to the same .aspx page wrapped in a script tag. Also within this section is the Page_Load method. The eventhandler is not within Page_Load.
The problem was found when I set a breakpoint and stepped through the code. Clicking my button shows that it doesn't hit my event handler at all. I don't know why this is, particularly as ASP created the event from clicking the button in Design mode.
Clicking my button shows that it doesn't hit my event handler at all.
This isn't all that surprising. ASP.NET MVC uses a completely different event model (i.e. it doesn't have one like web forms). However, what you're trying to do is very straight forward. In your controller build a new method, let's call it Undo:
public ActionResult Undo(int id)
{
RRSPSqlEntities db = new RRSPSqlEntities();
var updateAddress = (from a in db.Address
where a.PersonId == id
select a).SingleOrDefault();
updateAddress.Deleted = false;
db.SaveChanges();
return View("{insert the original action name here}");
}
and then in your markup, simply markup the input like this:
<form method="POST" action="/ControllerName/Undo">
#Html.HiddenFor(Model.Id)
<input type="submit" value="Undo" />
</form>
where the Model for the View you're on contains a property, I've called it Id, that is the id you want passed into Undo.
I usually prefer to make ajax calls. You can try:
<button type="button" class="button" onclick="ButtonUndo();" />
In the form:
<script>
function ButtonUndo() {
$.ajax({
type: 'POST',
url: '/controller/action',
data: 'PersonID=' + ID,
dataType: 'json',
cache: false,
success: function (result) {
//do stuff here
},
error: function () {
//do error stuff here
}
});
}
</script>
Controller:
[HttpPost]
public ActionResult Action(int PersonID)
{
//Do your stuff here
return new JsonResult { result = "something" };
}
(Sorry for any typos or syntax errors...I pulled from existing code that we use in a project.)
Let's say I have a view with Kendo treeview bounded to remote data source.
#(Html.Kendo().TreeView()
.Name("schemas")
.DataTextField("name")
.DataSource(dataSource => dataSource.Read(read => read.Action("Schemas", "Forms")))
.Events(events => events
.Select("onSelected")))
So the treeview just makes a call to the Schemas action in my FormsController
Also on the same page I have a form, which is simply the textbox and a button to submit the form
#using (Html.BeginForm("Load", "Forms", FormMethod.Post))
{
<div id="rootNode">
#Html.TextBox("rootElementName")
#Html.Button("next")
</div>
}
So I am just wondering what is the best way to handle user input and pass it to the the Load action of the FormsController? The user should select one of the options in the treeview and enter the value into textbox.
Or should I create some sort of viewmodel for my view with all my nodes inside + two additional fields for the textbox input and selected node?
I would take out the form elements, leaving:
<div id="rootNode">
#Html.TextBox("rootElementName")
#Html.Button("next")
</div>
The following js, this will pick up the tree item id on select.
The second function will call your Form controller action with the parameters.
<script>
var selectedNodeid;
//get the tree selected item id
function onSelected(e) {
var data = $('#schemas).data('kendoTreeView').dataItem(e.node);
selectedNodeid = data.id;
}
//button on click event
$(document).ready(function () {
$("#next")
.bind("click", function () {
//get parameters then pa
var id = selectedNodeid;
var rootElementName = $('#rootElementName).val()
$.ajax({
url: "Form/Load",
data:{id:id,rootElementName:rootElementName},
success: function () { }
});
}
})
</script>
I haven't tested this but it should be close.
I look forward to someone adding a better approach.