UpdatePanel Breaks JQuery Script on datalist - javascript

I have an update panel and inside the update panel I have a datalist.
On the datalist I have multi div
<div class="prod_details_tab">
<div class="prod_details_sell">
<a href="Handler.ashx?action=addToBasket&productID=4" onclick="return false;">
<img src="images/cart.gif" alt='<%#String.Format("{0}", Eval("k_name1")) %>'
width="16" height="16" id='<%#String.Format("{0}", Eval("k_name1")) %>'
class="left_IB" />
</a>
</div>
</div>
I write a jQuery code that when a person click on cart.gif pic run the jQuery
$(".prod_details_sell a img").click(function () {
//some code is here
});
On the first page of datalist jquery run good and all thing is ok.
But on the second page when I click on cart.gif pic jQuery does not run.
Please help me to fix it
Thanks
Edit: I write next button and prev button click in here
protected void cmdNext_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage += 1;
PagedDataSource pagedDS = new PagedDataSource();
pagedDS.DataSource = ((DataTable)Cache["DataTable-cach"]).DefaultView;// cacheItem.DefaultView;
pagedDS.AllowPaging = true;
pagedDS.PageSize = 6;
pagedDS.CurrentPageIndex = CurrentPage;
dlPaging.DataSource = pagedDS;
dlPaging.DataBind();
// Disable Prev or Next buttons if necessary
cmdPrev.Enabled = !pagedDS.IsFirstPage;
cmdNext.Enabled = !pagedDS.IsLastPage;
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
PagedDataSource pagedDS = new PagedDataSource();
pagedDS.DataSource = ((DataTable)Cache["DataTable-cach"]).DefaultView;// cacheItem.DefaultView;
pagedDS.AllowPaging = true;
pagedDS.PageSize = 6;
pagedDS.CurrentPageIndex = CurrentPage;
dlPaging.DataSource = pagedDS;
dlPaging.DataBind();
lblCurrentPage.Text = pagedDS.PageCount.ToString() + " صفحه " + (CurrentPage + 1).ToString() + " از ";
// Disable Prev or Next buttons if necessary
cmdPrev.Enabled = !pagedDS.IsFirstPage;
cmdNext.Enabled = !pagedDS.IsLastPage;
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}

thank you friends
I edit html file
<ContentTemplate>
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
.
.
.
and edit my jquery file
function BindEvents() {
//my jquery codes
}
Be Happy

When you go to next page of data list the onclick event gets unbinded as update panel refresh the content inside div. So onclick event must be added again to get the expected result.
Try the following in cs page below your datalist bind code.
ScriptManager.RegisterClientScriptBlock(id of update panel,
typeof(UpdatePanel), "string",
"$(function () {$('.prod_details_sell a img').click(function () {
//some code is here
});)", true);

Just replace this:
$(".prod_details_sell a img").click(function () {
//some code is here
});
with this:
Sys.Application.add_load(initJavaScripts);
function initJavaScripts() {
$(".prod_details_sell a img").click(function () {
//some code is here
});
}

Related

How to get List item's attribute in context menu's selection? Telerik

I am working with ASP.NET and I have two RadListBox. Data in first box is populated from database using RadListBoxItem and I have set an attribute for each item. In the second box, I've enabled custom context menu. After I adding the item from first box to second box, user can select some option using the context menu. On context menu selection, I need to get the Attribute I set before and update the attribute value according to the context menu selection so I can used it for later process.Currently, I unable to even read the attributes I set previously using the context menu's javascript. Please guide how to read ListItem's attribute and update the attribute to a new value.
This is how I add the item to the first box with attribute from code behind.
this._sortingList = new List<Sorting>();
this._sortingList = DBConnection.getSortingList();
foreach (var s in this._sortingList)
{
RadListBoxItem item = new RadListBoxItem();
item.Text = s.Description;
item.Value = s.Id.ToString();
item.Attributes["myorder"] = "0";
this.RadListBox1.Items.Add(item);
}
This is custom context menu javascript.
function showContextMenu(sender, e) {
var menu = $find("<%= cm1.ClientID %>");
var rawEvent = e.get_domEvent().rawEvent; menu.show(rawEvent);
e.get_item().select();
$telerik.cancelRawEvent(rawEvent);
}
function onItemClicked(sender, e) {
var listBox = $find("<%= RadListBox1.ClientID %>");
var listItem = listBox.get_selectedItem();
var menuItem = e.get_item();
if (menuItem.get_text() == "Ascending"){
alert(listItem.get_attributes().getAttribute("myorder"));
}
else if (menuItem.get_text() == "Descending") {
alert(listItem.get_attributes().getAttribute("myorder"));
}
}
The context menu's if else statement is working. I tested with some random alert and it can work. Sorry for my English.
Add the following property to RadListBox.
OnClientContextMenu="list_ClientContextMenu"
Declare a RadContenxtMenu as follows.
<telerik:RadContextMenu ID="cmEdit" runat="server" OnClientItemClicked="cm_ClientItemClicked" Skin="Vista">
<Items>
<telerik:RadMenuItem Text="Edit" Value="e">
</telerik:RadMenuItem>
</Items>
</telerik:RadContextMenu>
Add a hidden field to get the client ID.
<asp:HiddenField runat="server" ID="hdnCmSelectedList" />
Finally add the JS to handle it.
function list_ClientContextMenu(sender, e) {
var menu = $find("<%= cmEdit.ClientID %>");
var rawEvent = e.get_domEvent().rawEvent; menu.show(rawEvent);
e.get_item().select();
var listName = sender.get_id();
if (listName.indexOf('listEmail') != -1) {
$get("<%= hdnCmSelectedList.ClientID %>").value = 'pe';
}
function cmEditAdmin_ClientItemClicked(sender, e) {
$find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>").ajaxRequestWithTarget("<%= lnkBtnEdit.UniqueID %>", '');
}
Add a button with click handler as well.
<asp:LinkButton runat="server" ID="lnkBtnEdit" OnClick="lnkBtnEdit_Click"></asp:LinkButton>
Now in the code behind.
protected void lnkBtnEdit_Click(object sender, EventArgs e)
{
RadListBoxItem item;
switch (hdnCmSelectedList.Value)
case "pe":
item = list.SelectedItem;
if (item != null)
{
comboPendingDurationEmail.FindItemByValue(item.Attributes["myorder"]).Selected = true;
}
break;
}
Let me know, how that works out.

Loading selected GridView Item in Popup using CallBacks with ASP.Net MVC

I still relatively new to ASP.Net and the concepts of communicating between client and server. I am using DevExpress tools but I believe this issue is more of a misunderstanding of the concept.
I have a GridView within a partial view that is loaded via an Action #Html.Action('MessageGridView'). This works no problem and data is loaded fine with the index and a returned model.
#Html.DevExpress().GridView(settings =>
{
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Name = "preparedMessagesGrid";
settings.CallbackRouteValues = new { Controller = "Messages", Action = "MessagesGridView" };
settings.KeyFieldName = "Id";
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
settings.ClientSideEvents.Init = "GridViewInit";
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
settings.ClientSideEvents.BeginCallback = "OnBeginCallback";
settings.SettingsBehavior.AllowEllipsisInText = true;
settings.PreRender = settings.Init = (sender, e) =>
{
MVCxGridView gridView = sender as MVCxGridView;
gridView.Selection.SelectAll();
};
settings.Columns.Add("Name");
settings.Columns.Add("Description");
}).Bind(Model.preparedMessages).GetHtml()
What I am trying to achieve is when the user selects the row I wish the data to be loaded into the popup control when clicked. Is there a way I can set the parameters dynamically for the popup control callback?
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "pcModalMode";
settings.Width = 100;
settings.AllowDragging = true;
settings.CloseAction = CloseAction.CloseButton;
settings.CloseOnEscape = true;
settings.PopupAnimationType = AnimationType.None;
settings.HeaderText = "Login";
settings.Modal = true;
settings.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
settings.PopupVerticalAlign = PopupVerticalAlign.WindowCenter;
settings.CallbackRouteValues = new { Controller = "Messages", Action = "Load", new { id = THIS NEEDS TO BE SELECTED ID VALUE} };
settings.LoadContentViaCallback = LoadContentViaCallback.OnFirstShow;
}).GetHtml()
It works if I set the value static so I'm one step away from getting this working. What I have researched is that I can get the values from the GridView in javascript using the selection changed event.
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues("Id", GetSelectedFieldValueCallback);
}
I can then retrieve this value but can I set this to my popup control or am I misunderstanding being relatively new and possibly I could do this server side for when the ViewGrid callback is performed, then set it server side with a session of some sort?
You're just one step away to get currently selected grid value with this function:
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues('Id', GetSelectedFieldValueCallback);
}
What you need to do is declaring GetSelectedFieldValueCallback method as this (I got from a test that selectedValue contains array with single value for single grid row selection, use zero index to assign the value):
var id; // a global variable set to hold selected row key value from grid
function GetSelectedFieldValueCallback(selectedValue) {
if (selectedValue.length == 0)
return;
id = parseInt(selectedValue[0]);
pcModalMode.PerformCallback();
}
Then setting BeginCallback on PopupControl helper as given below, note that for DevExpress HTML helpers you can use customArgs in client-side to pass action method parameters instead of using CallbackRouteValues with id parameter:
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "pcModalMode";
// other stuff
settings.CallbackRouteValues = new { Controller = "Messages", Action = "Load" };
settings.ClientSideEvents.BeginCallback = "OnPopUpBeginCallback";
settings.ClientSideEvents.EndCallback = "OnPopUpEndCallback";
// other stuff
}).GetHtml()
// JS function for popup callback
function OnPopUpBeginCallback(s, e) {
e.customArgs["id"] = id; // this sends 'id' as action method parameter to `Load` action
}
// Optional end callback
function OnPopUpEndCallback(s, e) {
if (!pcModalMode.IsVisible())
pcModalMode.Show();
}
Finally, let's putting them all together in view & controller code:
View
<!-- View page -->
<script type="text/javascript">
var id;
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues('Id', GetSelectedFieldValueCallback);
}
function GetSelectedFieldValueCallback(selectedValue) {
if (selectedValue.length == 0)
return;
id = parseInt(selectedValue[0]);
pcModalMode.PerformCallback();
}
function OnPopUpBeginCallback(s, e) {
e.customArgs["id"] = id;
}
function OnPopUpEndCallback(s, e) {
if (!pcModalMode.IsVisible())
pcModalMode.Show();
}
</script>
GridView (partial view)
#Html.DevExpress().GridView(settings =>
{
settings.Name = "preparedMessagesGrid";
// other stuff
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
}).Bind(Model.preparedMessages).GetHtml()
Popup (partial view)
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "pcModalMode";
// other stuff
settings.CallbackRouteValues = new { Controller = "Messages", Action = "Load" };
settings.ClientSideEvents.BeginCallback = "OnPopUpBeginCallback";
settings.ClientSideEvents.EndCallback = "OnPopUpEndCallback";
// other stuff
}).GetHtml()
Controller
public class Messages : Controller
{
public ActionResult MessagesGridView()
{
// grid view populating data code lines here
return PartialView("_GridView", data);
}
public ActionResult Load(int id)
{
// code lines to find ID here
return PartialView("_ModalPopup", model);
}
}
References:
(1) Display GridView Row Details in PopupControl Window
(2) How to display detail data within a popup window (MVC)
(3) ASPxClientGridView.GetSelectedFieldValues (DevExpress Documentation)
(4) MVCxClientBeginCallbackEventArgs.customArgs (DevExpress Documentation)

Calling event click with JavaScript

It is possible to call a event click with JavaScript? how?
I'm trying to call this event when a button get clicked.
I'm creating Buttons dynamically so the id's change constantly
Here is how i make the buttons dynamically and assign the event click
protected void Page_Init(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);
Button Btn_clic = (Button)sender;
var name = Btn_clic.Text;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();
List<Button> Botones = new List<Button>();
var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();
foreach (var team in TeamFCH)
{
Button newButton = new Button();
newButton.CommandName = "Btn" + Convert.ToString(team);
newButton.ID = "Btn_" + Convert.ToString(team);
newButton.Text = team;
newButton.CommandArgument = name;
newButton.Click += new System.EventHandler(newButton_Click);
Botones.Add(newButton);
GoodPanel.Controls.Add(newButton);
newButton.CssClass = "btn-primary outline separate";
}
}
protected void newButton_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);
Button Btnclick = (Button)sender;
var team = Btnclick.Text;
string name = Btnclick.CommandArgument;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();
var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
Grv_Eng.DataSource = ListOfToolsOk;
Grv_Eng.DataBind();
}
If you want to assign a OnClick event, do it like this.
Button Btnclick = new Button();
Btnclick.Click += newButton_Click;
Btnclick.Text = "MyButton";
Btnclick.ID = "MyButtonID";
PlaceHolder1.Controls.Add(Btnclick);
And if you want to reference the dynamic ID, use FindControl and ClientID on the aspx page.
document.getElementById("<%= PlaceHolder1.FindControl("MyButtonID").ClientID %>").click
Assign an onClick listener to your button.
document.getElementById("your-id").click = function () {
newButton_Click();
}
Here you go try this for dynamically created buttons
$(document).on('click', '#id', function(){});
You can use a data- attribute to id the buttons from javascript and then you just attach to the javascript event:
So, from the server side you can do this:
newButton.Attributes["data-dynamic-button"] = team;
And you can implement this on the client side:
$("[data-dynamic-button]").click(function (event) {
event.preventDefault()
alert($(event.currentTarget).data("dynamic-button"));
});

ASP.NET MVC -Refresh CodeMirror editor onclick

I have a codemirror editor in a partial view and a list of files in the main view. I want to refresh the editor once a file name is clicked. I tried many solutions provided on StackOverflow and other websites but nothing worked , and This is my first time using Javascript so I can't figure out What am I doing wrong.
This is my code:
Controller:
public ActionResult Index()
{
StudentsCodes model = new StudentsCodes();
model.Student = (Student)CurrentUser;
var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
model.Instructor =(Instructor) user;
return View(model);
}
public PartialViewResult DevelopmentPartial (StudentsCodes path )
{
return PartialView(path);
}
Main view:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<ul id="tree">
#foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
{
var filename = Path.GetFileName(file);
<li id="filelist" onclick="#(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + #filename)">
<span class="glyphicon glyphicon-file"></span>
#filename
/li>
}
<div id="partial">
#{
Html.RenderPartial("DevelopmentPartial",null);
}
</div>
<script>
$(document).ready(function () {
$("#filelist").click(function (e) {
#{Html.RenderAction("DevelopmentPartial", Model);
}
});
});
</script>
partial view:
#using (Html.BeginForm())
{
var fileContents= "";
if (Model==null)
{
fileContents = "";
}
else
{
fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
}
#Html.TextArea("code", fileContents, new { id = "code" })
}
I can't assign ids for list elements since their number is unknown at compile time and it changes when the user adds or deletes a file, that's why most of the solutions provided didn't work . The result here was 3 editors overlapping and display the contents of the last file. And <li> items are non-clickable. What am I doing wrong in my code ?
Edit:
After updating the script as the following:
<script>
$(document).ready(function() {
$(".filelist").on("click",function (e) {
$("#partial").load('DevelopmentPartial');
});
});
</script>
It refreshes the partial view but the editor is always empty, and the Model is always null. Is it wrong to update the Model using "onclick"?
In case someone faced the same problem, I solved it by changing id to class at the list, then by using this script:
<div id="partial">
#{
Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
}
</div>
<script>
$(document).ready(function () {
$('.filelist').on('click', function (e) {
alert('Im clicked on filePath = ' + $(this).attr('value'));
var filePath = $(this).attr('value'); //value is attribute set in Html
$('#partial').load('DevelopmentPartial', { path1: filePath });
});
});
</script>
And the controller:
public PartialViewResult DevelopmentPartial(string path1)
{
modelSC.path = path1;
return PartialView(modelSC);
}
where modelSC is a global variable in the controller.

Checkbox Check changed event firing twice C#

I have a listview with checkbox. According to my requirement I uncheck through javascript. But because of that script my Checkchanged event fires twice and returns the previous unchecked(through javascript) value on second time fires.
Also usually any operation check box triggers an event. But if you check the same item which is unchecked through javascript just before is not fires the checkedchanged event.
I am not sure why is it happening when using script.
Please find the code below
JavaScript
function CallConfirmBox() {
alert("456");
if (confirm('Schedule more than one time slot for the same day will overwrite the file')) {
return true;
}
else {
var id = document.getElementById('<%= hdnValue.ClientID%>').value;
alert(id);
$('#' + id).attr('checked', false);
alert("123")
id = "";
return false;
}
}
CodeBehind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkCheck = (CheckBox)sender;
ListViewItem item = (ListViewItem)chkCheck.NamingContainer;
ListViewDataItem dataItem = (ListViewDataItem)item;
string lookupId = lvLookup.DataKeys[dataItem.DisplayIndex].Value.ToString();
hdnValue.Value = chkCheck.ClientID;
if (lookupMstVal == "ScheduledTime." && lbCheckedIdList.Items.Count > 0 && chkCheck.Checked)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);//" + chkCheck.ClientID + "
}
if (chkCheck.Checked)
lbCheckedIdList.Items.Add(lookupId);
else
lbCheckedIdList.Items.Remove(lookupId);
hdfLookupId.Value = "";
foreach (ListItem itm in lbCheckedIdList.Items)
{
hdfLookupId.Value += (hdfLookupId.Value == "" ? "" : ",") + itm.Value;
}
postbackFlag = true;
}
Please Help! Thanks.

Categories

Resources