jQuery Mobile button is not firing without refresh - c#

I am using jQuery mobile in my project and when I log on to system, then go to change password page, the change action is not firing (no action). But, when I refresh the page, it is firing. Briefly, the button on the page is not working when it is redirected from another page except itself. I have imported .css and .js files correctly in master page. (Generic Handler returns correct values and it is working)
head content:
<script type="text/javascript">
$(document).ready(function () {
$("#changePasswordBtn").click(function () {
$.ajax({
type: "POST",
url: "ChangePasswordHandler.ashx",
data: "oldPassword=" + $("#oldPassword").val() + "&newPassword=" + $("#newPassword").val() + "&reNewPassword=" + $("#reNewPassword").val(),
success: function (msg) {
if (msg == 0) $("#popupText").text("success");
else if (msg == 1) $("#popupText").text("wrong pass");
else if (msg == 2) $("#popupText").text("match error");
else if (msg == 3) $("#popupText").text("fill boxes");
else $("#popupText").text("error");
}
});
})
});
</script>
body content:
<input type="button" id="changePasswordBtn" value="Change Password" data-inline="true" />

I have seen a similar problem in my project. Make sure that you are using different ids for buttons.
If the ids are same then the click event is not attached to the right button.

I got a workaround for this issue by changing the way I load my pages.
I put target="_self" into the href element so it don't load using the # system - this way the javascript loads with the initial page load while navigating from one page to a nother.
I will put the below link on my index.html page that will navigate to my signup.html page.
Signup
NOTE: You will lose the 'fancy' jQuery Mobile page transition feature

Related

.aspx & c# how to change URL value

I am having some trouble with a URL value that's set, I have below URL:
http://localhost/myapp/Admin/ScheduleTaskDetail.aspx?id=1&mode=v
The modes are:
v - View
e - Edit
a - New
I want to allow changes to the view page so when I click a button they can edit. I have managed to get this working by using the function that reads from the URL and changing its behavior there. However I don't know how to update the URL without a response.redirect().
Is there a way to add code to a onclick event that will change the &mode=??
Unfortunately, I can't share code as its not my code to share.
This is part of a MVC c# / aspx project.
If there is a question answering this please let me know I couldn't find a match that was applicable.
Change Browser URL without reloading using JavaScript
The HTML Markup consists of 3 buttons which make a call to a function ChangeUrl. This function accepts the page Title and URL as parameters.
It first checks whether browser supports HTML5 and if yes then a State object containing the page Title and URL is created and is passed to the HTML5 History pushState method along with the page Title and URL as the other two parameters.
<script type="text/javascript">
function ChangeUrl(title, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Title: title, Url: url };
history.pushState(obj, obj.Title, obj.Url);
} else {
alert("Browser does not support HTML5.");
}
}
</script>
<input type="button" value="Page1" onclick="ChangeUrl('Page1', 'Page1.htm');" />
<input type="button" value="Page2" onclick="ChangeUrl('Page2', 'Page2.htm');" />
<input type="button" value="Page3" onclick="ChangeUrl('Page3', 'Page3.htm');" />
Change Browser URL without reloading using jQuery
The HTML Markup consists of 3 buttons to which the jQuery click event handler has been assigned. Inside the jQuery click event handler, a function ChangeUrl is being called which accepts the page Title and URL as parameters.
This function first checks whether browser supports HTML5 and if yes then a State object containing the page Title and URL is created and is passed to the HTML5 History pushState method along with the page Title and URL as the other two parameters.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
} else {
alert("Browser does not support HTML5.");
}
}
$(function () {
$("#button1").click(function () {
ChangeUrl('Page1', 'Page1.htm');
});
$("#button2").click(function () {
ChangeUrl('Page2', 'Page2.htm');
});
$("#button3").click(function () {
ChangeUrl('Page3', 'Page3.htm');
});
});
</script>
<input type="button" value="Page1" id="button1" />
<input type="button" value="Page2" id="button2" />
<input type="button" value="Page3" id="button3" />
Perhaps a better approach instead of trying to shoe horn in the use of URL query strings is to just use a control on the page which triggers the V, E, A values and fires the appropriate event depending on what the user clicks/selects. So for example a dropdownlist with V, E, and A. User selects the value they want then the binding is done at the selectedindexchange event. You can use updatePanels if you only want to refresh a applicable section of the page.

How to render any event function on page load in mvc4

In select tag, there is a function loadTags(), which is called on onclick event. I am using mvc4 and want to call it with _layout.cshtml i.e shared view:
<div class="left-menu">
<select id="tid" name="tags" onclick="loadTags()" >
<option value="tags">--Tags--</option>
</select>
</div>
How should I call this function on page load. Here is loadTags() function
function loadTags() {
$("#tid option").remove();
var d = $("#tid").val();
var str = "--Tags--";
$.post("/Status/allTags", function (data) {
$("#tid").append('<option>' + str + '</option>');
$.each(data, function (i, item) {
$("#tid").append('<option value=' + i + '>' + item + '</option>');
});
}, "json");
}
Just use jQuery?
$(function() {
loadTags();
});
Make sure jQuery is loaded before you call this line of code.
I don't think loading the tags when the user clicks the element is a good approach. For instance, when the user uses the tab key to navigate to this element, the tags will not load.
Also, if you are loading the tags on page load, does it still make sense to load them via AJAX? Can't you include them in the page itself?
put your code in document.ready function:
$(document).ready(function () {
loadTags();
});
or shorter:
$(function () {
loadTags();
});
or even shorter:
$(loadTags);
jfiddle
.ready():
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received. In most cases, the
script can be run as soon as the DOM hierarchy has been fully
constructed. The handler passed to .ready() is guaranteed to be
executed after the DOM is ready, so this is usually the best place to
attach all other event handlers and run other jQuery code. When using
scripts that rely on the value of CSS style properties, it's important
to reference external stylesheets or embed style elements before
referencing the scripts.

jquery tab asp.net staying on tab after postback 0x800a01b6

Hello i need to stay on a jquery tab after asp.net postback, but nothing what i found here or somewhere else in the web works for me.
I tried:
Staying on current jQuery tab across post back?
and
Jquery postback, maintain same tab after postback
but also some other sources.
Everytime when im changing
$("#tabs").tabs();
to something like:
$(function () {
$("#tabs").tabs({
show: function() {
var selectedTab = $('#tabs').tabs('option', 'selected');
$("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
},
selected: <%= hdnSelectedTab.Value %>
});
});
With hiddenfield etc. i get this error 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tabs'.
When im Using the jquery.cookie.js file with this code:
$("#tabs").tabs({ cookie: { expires: 1 } });
i dont get an error but i dont stay on the tab after postback.
You can give your input button a css class.
#inputField {
display:none !important;
}
Save this as yourCssClass.css
document.getElementById("inputField ").className += "yourCssClass";
Add this to your JavaScript
I found out what the Problem was, I inserted jquery on the end of my master page because of that somehow it overwrote the jqueryui file in that specific aspx file. After i added the jqueryui.js file after the jquery.js everything worked fine.

asp.net mvc and webforms use two button

My problem is I'm trying do something to on mvc webforms
page name = addition.aspx
event = button1_click
int numberOne = convert.toint32(textbox1.text);
int numberTwo = convert.toint32(textbox2.text);
int myResult = numberOne + numberTwo;
label1.text = myResult.Tostring();
.
page name = addition.aspx (same page)
event = button2_click
int numberthree = convert.toint32(textbox3.text);
int numberfour = convert.toint32(textbox4.text);
int myResult2 = numberOne + numberTwo;
label2.text = myResult2.Tostring();
my question is I want to do sameting for MVC ( where is event ... i guess i have to conversion on the page post and page get ... am i wrong)
You don't have server side controls for MVC. If you are wanting to have two buttons trigger different events you have a couple options. JQuery is included in your MVC project by default, and it's very popular. So I will show you some examples with that.
Create the two submit buttons to toggle the form action before submit.
Example using jquery:
HTML
<form action="">
<input type="submit" id="first" value="first" />
<input type="submit" id="second" value="second" />
</form>
JS
$(function(){
// on document ready wire up click events
// handle click event for first button
$('#first').on('click', function(){
$('form').prop('action', 'PostActionOne'); // set the action on the form to handle first button post
});
// handle click event for second button
$('#second').on('click', function(){
$('form').prop('action', 'PostActionTwo'); // set the action on the form to handle second button post
});
});
Another option:
Use two buttons with a click event that executes an ajax request to handle the scenario.
HTML
JS
$(function(){
// on document ready wire up click events
$('#first').on('click', function(){
$.ajax({
type: 'POST',
url: 'PostActionOne,
data: data,
success: success,
dataType: dataType
});
});
$('#second').on('click', function(){
$.ajax({
type: 'POST',
url: 'PostActionTwo,
data: data,
success: success,
dataType: dataType
});
});
});
ASP.NET WebPages indeed may offer better event driven programming(arguably), but nevertheless it does not run on the client side. So regardless if you use WebForms or MVC if you want something to take place on the click event of a button located on a browser webpage, make the triggers in javascript, jquery, and use ajax so you don`t have to reload the entire page each time.
Also in mvc you have a helper called
#Ajax.ActionLink("linkname", "Action", "etc");
that can get you working pretty fast, just read about it.
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.actionlink%28v=vs.108%29.aspx

How to create stackoverflow's post voting like jquery/ajax function?

Can I use Jquery to call an action and then change the image when it success, just like stackoverflow's post voting function?
In my view, I'm using the following code, but I don't want to refresh the browser. Can anyone provide some code about this for me?
Many thanks.
<%if (!item.IsPrinted)
{ %>
<%=Html.ImageLink("~/Content/images/web/delete.png", "printed", "MarkAsPrinted", "Order", item.TaskID, null, null)%>
<%}
else
{%>
<img src="~/Content/images/web/star.png" alt="printed" />
<% } %>
Generally you should call helper methods through ajax call for this purpose rather than calling your action through ajax. Then, in the helper method, update the value of the score (like storing the latest value to the databse etc) and in the success method of ajax display the appropriate image
Edit:
public string UpdateVoteScore(int postId, int value) {
// store value to database
return "success";
}
In JavaScript:
var UpdateScore = function(postId, newValue) {
$.ajax({
type: "POST",
url: /YourController/UpdateVoteScore,
data: { postId: postId, value: newValue },
success: function(result) {
// replace your image
$("#MyImage" + postId).attr("src", "some new image path here");
},
error: function(req, status, error) {
}
});
}
In View:
<img id='<%= "MyImage" + post.Id %>'
src="some image path"
onclick="UpdateScore(scoreValueHere);"></img>
Note: post will be changing as you do this in a loop, so the post.Id will be unique and thus makes the image id unique
Yes you can use JQuery for this. For example by letting JQuery replace a part of you're HTML code based on what it get's back from the server script.
Sample:
<html>
<head>
<script type="text/javascript" src="jquery-1.3.1.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#response a').bind('click',function(event){
event.preventDefault();
$.get(this.href,{},function(response){
if (response.indexOf("OK") >= 0) {
$('#response').html("<img src="~/Content/images/web/star.png" alt="printed" /> ");
}
})
})
});
</script>
</head>
<body>
... the other things on you're page
<div id="response">
<%=Html.ImageLink("~/Content/images/web/delete.png", "printed", "MarkAsPrinted", "Order", item.TaskID, null, null)%>
</div>
... more things on you're page...
</body>
</html>
Make sure that the server script returns "OK" when it needs to replace what's in the "respone" div.
I'm not sure you fully understand exactly what ajax is or does.
The way requests are normally made without ajax is essentially this:
[browser request]->[server handles request]->[new page sent to browser]
The difference with ajax is that a request is sent to the server, and the response is received by javascript, without the page reloading or anything. It is then up to the javascript script to decide what to do once the request has been received.
What you'd do for this is send the request to 'vote.asp' or something, and then use javascript to change the image once you receive the response from the server.
You could probably do something like:
$('#vote_button').click(function() {
$.ajax({
type: "GET",
url: "script_name.asp", //your script that talks to the database
data: "id=" + some_var, //get arguments
success: $("#image_to_be_changed").attr("src", "some new image path here");
});
I created a simple voting application similar to stackoverflow.com using angularjs,php and mysql with code to download. You just need to change the 2 php files into ASP.NET files. Everthing else will be intact. Creating the voting app using AngularJS is much easier and flexible.

Categories

Resources