ASP .NET MVC; return HTML along with JavaScript - asp.net

I have a partial view which renders a table.
On page load, I am using JQuery to perform Zebra Stripping on it.
Whenever ajax refreshes the table, DOM elements are updated, but since JQuery code to do the Zebra Stripping is not executed; table looks ugly.
I have tried adding Javascript in my partial view
if( Request.IsAjaxRequest() )
return PartialView( "AdministrationGrid", Users );
but javascript is not executed.
I guess the only way to execute the Javascript as reply is to do:
return JavaScript( "alert( '' )" );
Anyone with an idea how can I achieve this?
I thought about JQuery Live, but it is used to bind itself to events.

Surely if you are using AJAX to refresh the table, you have a function that gets called to request your data. If there is an onSuccess function, you could just call the striping in there.

Related

Register JavaScript alert at extreme end using RegisterStartupScript

(Note: Just to clarify the problem is not specifically related to C1WebDateEdit. It could be with any custom control which require JavaScript to render actual control)
I have many C1WebDateEdit controls in my page. On a button click based on some condition I am displaying JavaScript alert message ScriptManager.RegisterStartupScript. These controls are inside UpdatePanel. The issue I am facing with it is, when these C1WebDateEdit has not value and page displays alert message, it displays "01/01/0001" behind the alert box and on closing alert it shows empty textboxes.
The reason is, C1WebDateEdit creates actual control using JavaScript. and page renders alert message JavaScript before C1WebDateEdit controls' JavaScript.
For example:
HTML markup
alert JavaScript
C1WebDateEdit JavaScript
Logical solution is get alert JavaScript after C1WebDateEdit JavaScript because it will allow C1WebDateEdit to load fully before alert box.
I found no inbuilt way in asp.net to change sequence, so I tries solution given here but It didn't work for me.
One possible solution I am thinking that I create Custom or WebUserControl and place at it last at the page in the UpdatePanel and PreRender event I call ScriptManager.RegisterStartupScript to register alert message. Logically I think it will work but trying to find that any one implemented any other solution for it?.
Other possible solution is use "pageLoaded" event of PageRequestManager. I created below function for temporary fix:
function delayedAlertBox(strMsg)
{
var fnc = function (a, b)
{
//remove reference so on next call it do not show previous alerts.
Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(fnc);
alert(strMsg);
}
//add function reference to call on Ajax pageloaded event
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(fnc);
}
and calling in asp.net like simple function as given below:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "dd", "delayedAlertBox('Hi, how are you?')", True)
But still looking for any other good alternative. If I found other, I will post it.

how can i apply complete css on ajax response using jquery

We are building a single page application using jQuery Mobile framework. the scenario we have is that we dont want to use the default behavior of having href links being hijacked and rendered as ajax response because practically, the page change causes the screen to flicker a bit and we dont want that to happen. so, to avoid that, we shall write our own ajax calls to the server to get specific data and update the content on page using the response from the server. However, in doing so any javascript that needs to be bound on the response AND the Css styling on the response HTML is completely lost.
Can somebody please advise what would be the best way to rebind / refresh the JS & CSS for the html received via Ajax.
Read "Enhancing new markup" in the JQM documentation. The trigger('create') event should solve this:
$( ...new markup that contains widgets... ).appendTo( ".ui-page" ).trigger( "create" );

How to run a javascript function before postback of asp.net button?

I'm using Javascript to create a DIV element and open up a new page by using onclientclick. This works great. Now, I need to write to it from the server side and this element must be created before it is posted back.
How do I get the javascript to execute before the postback?
Currently, I have to press the button twice because the element doesn't exist to write too on the first click.
To be clear, I need this to execute before the "OnClick" of the button.
Update: It looks like the Javascript function is called before the postback but the element is not updated until I run the second postback. Hmm
Update: Unfortunately it is a bit more complicated then this.
I'm creating a div tag in javascript to open a new window. Inside the div tag, I'm using a databinding syntax <%=Preview%> so that I can get access to this element on the server side. From the server side, I'm injecting the code.
I'm thinking this may be a chicken-egg problem but not sure.
UPDATE!
It is not the Javascript not running first. It is the databinding mechanism which is reading the blank variable before I'm able to set it.
Hmm
you don't have to rely on server controls to perform postbacks in asp.net. you can gain finer control of your app by posting from javascript whenever you are ready..
the framework auto generates a function called __doPostback(.....) and eventually calls it every time it needs to do a postback.
so. instead of using server control button, you can have a regular <button onclick="foo()" />
than once you're done performing all that you need, just call the __doPostback function.
asp.net gives you a nifty way to access that function with
Page.GetPostbackClientEvent (i believe, but there are couple methods that support this methodology)
http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackclientevent.aspx
enter code hereWould this work for you?
Javascript
function stuffYouWantToDo(){
//do your stuff
//then submit the .NET form
document.forms[0].submit();
}
.NET code
<asp:button ID="Button1" onClientClick="return false;stuffYouWantToDo();"/>
This should ensure that the stuff you want to do is done, then the form will be submitted. The return false prevents the form from being submitted when you first click the button and relies on the call in the stuffYouWantToDo function to submit the form.
If you want to use jquery you could do the following:
$(document).ready(function() {
var execScript = $(".myButton").attr("href").replace("javascript:", "");
$(".myButton").attr("href", "#").click(function() {
// Add before click logic here
eval(execScript);
});
});
Couldn't you simply add a custom validator somewhere in your form?

Using Javascript to detect when a user has selected an item in an ASP.NET listbox

I am developing an ASP.NET web application that incorporates google maps. I have an ASP.NET listbox on my page which contains a list of items. When the user selects one of the items, I'd like to show this item on the map. The main complication lies in the fact that google maps uses javascript to control it and the listbox is a server control.
I can think of two ways to do this. The first would involve the listbox calling a javascript function when the user selects a new item. I can then write this function to perform the necessary map operations. Unfortunately, the OnSelectedIndexChanged property of the listbox doesn't seem to support javascript functions.
The second involves wrapping an UpdatePanel around the listbox and getting the listbox to perform a postback. In the SelectedIndexChanged event in VB/C#, I would the need to somehow make a call to a javascript function which would then update the map.
Which solution can I use?
Thanks
--Amr
In your codebehind (in your pageload) just add a javascript handler to the OnChange attribute that points to your javascript function. Eg:
lbYourListBox.Attributes.Add("onChange", "UpdateYourMap();");
You could also add this to your control using inline javascript as well but I prefer to do it in the codebehind so that the framework can handle matching up the names.
You could simply embed javascript into your page, avoidig relying on ASP with it. Put the code into your document body:
<script language="javascript">
body.onload=function(){
var lb=document.getElementById("yourlistboxid");
lb.onChange = function(){
// put your handling code here
}
}
</script>
to demo the other approach, here's a rough guide:
void listbox_SelectedIndexChanged( ... ) {
string js = string.Format("callToMapsFunction({0});", listbox.SelectedValue);
string scriptKey = "mapscript";
ScriptManager.RegisterStartupScript( listbox, typeof(ListBox), scriptKey
, js, true);
}
RegisterStartupScript runs whatever javascript you give it after the partial postback completes. you don't necessarily have to pass the listbox value- just whatever data you want to provide to the maps api. the first 3 items are for preventing the script from registering a bunch of times (as far as I know). the true at the end tells the scriptmanager to automagically add opening and closing tags around your js code.

SimpleModal breaks ASP.Net Postbacks

I'm using jQuery and SimpleModal in an ASP.Net project to make some nice dialogs for a web app. Unfortunately, any buttons in a modal dialog can no longer execute their postbacks, which is not really acceptable.
There is one source I've found with a workaround, but for the life of me I can't get it to work, mostly because I am not fully understanding all of the necessary steps.
I also have a workaround, which is to replace the postbacks, but it's ugly and probably not the most reliable. I would really like to make the postbacks work again. Any ideas?
UPDATE: I should clarify, the postbacks are not working because the Javascript used to execute the post backs has broken in some way, so nothing happens at all when the button is clicked.
Both of you were on the right track. What I realized is that SimpleModal appends the dialog to the body, which is outside ASP.Net's <form>, which breaks the functionality, since it can't find the elements.
To fix it, I just modified the SimpleModal source to append eveything to 'form' instead of 'body'. When I create the dialog, I also use the persist: true option, to make sure the buttons stay through opening and closing.
Thanks everyone for the suggestions!
UPDATE: Version 1.3 adds an appendTo option in the configuration for specifying which element the modal dialog should be appended to. Here are the docs.
All standard ASP.NET postbacks work by calling a __doPostBack javascript method on the page. That function submits the form (ASP.NET only really likes one form per page) which includes some hidden input field in which all the viewstate and other goodness lives.
On the face of it I can't see anything in SimpalModal that would screw up your page's form or any of the standard hidden inputs, unless the contents of that modal happened to come from a HTTP GET to an ASP.NET page. That would result in two ASP.NET forms being rendered into one DOM and would would almost certainly screw up the __doPostBack function.
Have you considered using the ASP.NET AJAX ModalPopup control?
Web browsers will not POST any disabled or hidden form elements.
So what's happening is:
The user clicks on a button in your dialog.
The button calls SimpleModal's close() method, hiding the dialog and the button
The client POSTs the form (without the button's ID)
The ASP.NET framework can't figure out which button was clicked
Your server-side code doesn't get executed.
The solution is to do whatever you need to do on the client (closing the dialog in this case) and then call __doPostback() yourself.
For example (where "dlg" is the client-side SimpleModal dialog reference):
btn.OnClientClick = string.Format("{0}; dlg.close();",
ClientScript.GetPostBackEventReference(btn, null));
That should hide the dialog, submit the form, and call whatever server-side event you have for that button.
#Dan
All standard ASP.NET postbacks work by calling a __doPostBack javascript method on the page.
asp:Buttons do not call __doPostback() because HTML input controls already submit the form.
got caught out by this one - many thanks to tghw and all the other contributors on the appendto form instead of body fix. (resolved by attributes on the 1.3 version)
btw: If anyone needs to close the dialog programmatically from .net - you can use this type of syntax
private void CloseDialog()
{
string script = string.Format(#"closeDialog()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
}
where the javascript of closedialog is like this....
function closeDialog() {
$.modal.close();
}
I have found the following works without modifying simplemodal.js:
function modalShow(dialog) {
// if the user clicks "Save" in dialog
dialog.data.find('#ButtonSave').click(function(ev) {
ev.preventDefault();
//Perfom validation
// close the dialog
$.modal.close();
//Fire the click event of the hidden button to cause a postback
dialog.data.find('#ButtonSaveTask').click();
});
dialog.data.find("#ButtonCancel").click(function(ev) {
ev.preventDefault();
$.modal.close();
});
}
So instead of using the buttons in the dialog to cause the postback you prevent their submit and then find a hidden button in the form and call its click event.
FWIW, I've updated the blog post you pointed to with come clarification, reposted here - the reasoning & other details are in the blog post:
The solution (as of my last checkin before lunch):
Override the dialog's onClose event, and do the following:
Call the dialog's default Close function
Set the dialog div's innerHTML to a single
Hijack __doPostBack, pointing it to a new function, newDoPostBack
From some comments I’ve seen on the web, point 1 needs some clarification.  Unfortunately, I’m no longer with the same employer, and don’t have access to the code I used, but I’ll do what I can.  First off, you need to override the dialog’s onClose function by defining a new function, and pointing your dialog to it, like this:
$('#myJQselector').modal({onClose: mynewClose});
Call the dialog's default Close function.  In the function you define, you should first call the default functionality (a best practice for just about anything you override usually):
Set the dialog div's innerHTML to a single – This is not a required step, so skip it if you don’t understand this.
Hijack __doPostBack, pointing it to a new function, newDoPostBack
function myNewClose (dialog)
{
dialog.close();
__doPostBack = newDoPostBack;
}
Write the newDoPostBack function:
function newDoPostBack(eventTarget, eventArgument)
{
var theForm = document.forms[0];
if (!theForm)
{
theForm = document.aspnetForm;
}
 
if (!theForm.onsubmit || (theForm.onsubmit() != false))
{
document.getElementById("__EVENTTARGET").value = eventTarget;
document.getElementById("__EVENTARGUMENT").value = eventArgument;
theForm.submit();
}
}
The new Jquery.simplemodal-1.3.js has an option called appendTo. So add an option called appendTo:'form' because the default is appendTo:'body' which doesn't work in asp.net.
Had the same problem, but {appendTo:'form'} caused the modal popup to be rendered completely wrong (as though I had a CSS issue).
Turns out the template I'm building on top of has includes that put other forms on the page. Once I set {appendTo:'#aspnetForm'} (the default Asp.net form ID), everything worked great (including the postback).
In addition to tghw's answer, this excellent blog post helped me: jQuery: Fix your postbacks in Modal forms -- specifically BtnMike's comment: "You also must not have CssClass=”simplemodal-close” set on your asp:button." Taking that off the class was the not-obvious-to-me solution.
-John
if you don want modify the SimpleModal source.
try this..
After you call the modal() method add this:
$("#simplemodal-overlay").appendTo('form');
$("#simplemodal-container").appendTo('form');
the SimpleModal plugin add two this to your markup.
'simplemodal-overlay' for the background
'simplemodal-container' containig the div that you whant as pop up modal.

Resources