I call another page with an id, which returns the data based on id. I need the result value in JavaScript.
Then I need to bind the result to current page content area and display it to the user.
Initially, the user clicks one link in current page, then the id of the link should be passed to another page, and processed some function and get result from db.
I want to display the result in current page.
I am using vs2010. How can I do this?
So, you already have solved your asp.net part (you have the page, right?).
What you can do is use jquery and make an ajax call to that page and process the result. If your page returns a the information in json or xml format, it's easy to use it to upgrade your current document in the browser.
Here you will find the documentation and some samples of Jquery ajax: http://api.jquery.com/jQuery.ajax/
Hope it helps.
function ajaxCall(id_from_your_page){
$.ajax({
type: "POST",
url: '/service.asmx/your_method',
data: { 'id', id_from_your_page },
dataType: "application/json; charset=utf-8",
success: function(result){
alert("i got your result: " + result);
}
});
}
the above code is better as you will use JQuery and POST method.
you may also like this-
function sendRequest(id) {
var xmlObj = null;
if(window.ActiveXObject) {
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlObj = new XMLHttpRequest();
}
if(!xmlObj) return;
var location = "http://localhost:8080/myapplication/mypage?id="+ id;
xmlObj.open("GET", location, true);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState==4 && xmlObj.status==200) {
doSomethingWithTheResponse(xmlObj.responseText);
}
}
xmlObj.send(null);
}
function doSomethingWithTheResponse(responseText) {
// write your own code to handle the response from the page.
}
All the best :)
You can get the Id/Data from other pages or Db like this....
<asp:LinkButton runat="server" Text='<%#Eval("Title")%>'OnClick='javascript:ShowEventDetails'CommandArgument='<%#Eval("EventID").ToString()%>);'/>
or
onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>'
ASPX:
<asp:Button ID="btnget" runat="server" Text="Create WR" onClientClick="<%# GetPopupScript() %>" />
Code-behind:
protected string GetPopupScript() {
return string.Format( "javascript:popUp('popup_createWR.aspx', '{0}', '{1}')", Eval( "dvc_nm" ), Eval( "data_orgtn_yr" ) ); }
or try this...
<asp:LinkButton ID="LinkButton5" OnClientClick='<%# "return fun1(""" + Eval("mid") + """);"%>' runat="server"><%#Eval("mname")%></asp:LinkButton>
Related
I am converting a web form to MVC C# razor project. I like to know how I will get the same functionality in Razor where it will create a link and sumbit the form into the same page. The web form code is -
<asp:LinkButton ID="lnkBtn_1" runat="server" Text='<%#Eval("Sales") %>' OnCommand="LinkButton1_Command" CommandArgument='<%#Eval("Sales") %>' ></asp:LinkButton>
Thanks in advance
Try this
#Html.ActionLink("buttonText", "ControllerAction", "YourController ",
new { #sales = YourModel.Parameter}, new { #class =yourcssclass" })
Your Controller
public class YourController : Controller
{
public ActionResult Index()
{
var model = YourDataToDisplay;
return View(model);
}
public ActionResult ControllerAction(int sales)
{
//.....
}
}
You can use ViewData to define ButtonText.
There are many ways to use link button in rezor ,try any of these
<button type="button" onclick="#("window.location.href='" +#Url.Action("ActionResult", "Controller") + "'")">
Link Button
</button>
<a href="#Url.Action("ActionResult", "Controller")">
Link Button
</a>
#Html.ActionLink("Text","ActionResult","Controller")
submitting form into the same page you have to use Ajax Begin Form or use simple json object with a ajax post method. Try like this
$("#btnSave").click(function (e) {
var urlpath = '#Url.Action("ActionResult", "Controller")';
$.ajax({
url: urlpath ,
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error !!!");
}
});
You can write an anchor tag. But clicking on the anchor tag usually does not submit the form, but triggers an HTTP GET request. So you need to write some java script to do the form submission.
<form action="Customer/Create">
Submit
</form>
Using jQuery and some unobtrusive javascript code to bind the click event on this anchor tag,
$(function(){
$("#linkToSubmit").click(function(e){
e.preventDefault(); // prevent the normal link click behaviour (GET)
$(this).closest("form").submit();
});
});
Now you can execute the code in your HttpPost action of Create action method in the Customer controller (because that is the form's action set to)
Another option is to keep the submit button inside your form and style it so that it looks like a link as explained in this answer.
if you are new to mvc then you need to check it's basic from MVC tutorials: Please follow below thread for convert your web app code to MVC
https://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink(v=vs.118).aspx
#Html.ActionLink("buttonText",new { controller = "ContreollerName", action = "ActionName",
#sales = "Your parameter" })
And then make a action result in your controller
I am not quite sure what I am doing wrong here, I have a page in my webforms project which uses jQuery accordion. When the page is loaded for the first time, the server side code fetches some data to populate a user control which is then added to my page as shown below. This works fine and I have no problem with this.
The problem is, I am trying to generate a similar thing on my client, using jQuery by simply creating the controls in jQuery ajax response function and then add to dvProjects
ASPX markup:
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
<div runat="server" id="dvProjects" class="dvAccordion">
</div>
</asp:Content>
jQuery AJAX code:
function AddUserProject() {
var projectDialog = $('.dvEditExhibition');
var projectName = projectDialog.find('.txtProjectName').val();
var projectDescription = projectDialog.find('.txtProjectDescription').val();
var project= JSON.stringify({
'projectId': "00000000-0000-0000-0000-000000000000",
'projectName': projectName,
'projectDescription': projectDescription
});
$.ajax({
type: "POST",
url: "PresentationService.asmx/AddUserProject",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: project,
success: function(response) {
var data = response.d;
console.log(data);
var h3Title = $('<h3/>', {
id: "h3ProjectTitle",
text:data.Name
});
var divWrapper = $('<div/>', {
});
var dvProjectImages = $('<div/>', {
class: "dvProjectImages"
});
var imgProjectImage = $('<img/>', {
id: "imgProjectImage",
class: "imgProjectImage"
});
var dvProjectDetails = $('<div/>', {
id: "dvProjectDetails",
});
var pProjectDescription = $('<p/>', {
id: "pProjectDescription",
class: "pProjectDescription",
text: data.Description
});
dvProjectImages.append(imgProjectImage);
dvProjectDetails.append(pProjectDescription);
divWrapper.append(dvProjectImages, dvProjectDetails);
var dvProjects = $('#dvProjects');
dvProjects.append(h3Title);
},
error: function(response) {
}
});
}
My problem is these controls are not added to dvProjects.
Update: you had a bug in your javscript too, refer to my comments.
That's because when you set a div to runat="server" every html element in it, becomes a Literal Control server side and they are persisted to view state.
When you post the page, the server side control rebuilds the runat="server" div with information in the postdata (view state).
When you add controls with jQuery they are not in the postData/ViewState, so when the server side code revuilds the div, it doesn't see the ones you added with jQuery.
To fix that, you would need to create a custom WebControl and implement IPostBackEventHandler. So instead of...
<div runat="server" id="dvProjects" class="dvAccordion">
You would have something like this,
<xyz:ProjectsControl runat="server" cssclass="dvAccordion" id="theProjects" />
Then to add a control to it, you would do something like
__doPostBack('<%= theProjects.UniqueID %>, 'someJsonStringHere');
Then in your IPostBackEventHandler implementation, you serialize the json string coming in and use that to determine what server side controls to add to the ProjectsControl.
WebControl has methods you can override, WriteBeginTag, WriteEndTag, and there you could write an opening div and closing div, so your web control would render as a div.
By adding a string property calledd "CssClass" to your webcontrol, you can use that to set the class. So in WriteBeginTag you would also write out the class attribute to the div using CssClass as the value.
I am creating registration page and doing null field validation on submit button click using jquery. if there is any error in form validation then i am preventing default method call using jquery, so it will not call code behind button click event.
Problem:
sometimes user double clicked on button and this is calling code behind button click event two times with two database row insertion having a same data.
I tried lots of solution but unfortunately i couldn't make any success.
Please help me to solve out this problem if you have any solution.
Thanks in advance,
Actually, i was preventing default server side method call in jquery when button is clicked using e.PreventDefault() method of jquery if validation is false.
Don't know what was the problem but when i set function on client click of button and return true/false based on validation instead of e.PreventDefault, trick worked great for me.
Thanks to all who comment on this question.
Simply add a variable called 'loading' for example and check if the ajax call is busy:
At the top of your code:
var loading = false;
Then on form submit:
$('#form').submit() {
if(loading)
return false;
loading = true;
//Ajax call
$.ajax({
type: "POST",
url: "somePage.php",
data: $('#form').serialize(),
success: function(response) {
loading = false;
//Your response code
}
});
}
Use one on the client side. This will prevent double clicks.
$("#button").one("click", function() {
// validate the form.
// if form is valid, submit form
});
An alternative solution is to have a boolean flag.
var submitting = false;
$("#button").click(function() {
if (!submitting) {
submitting = true;
if (formIsValid) {
submitting = false;
$("#form").submit();
} else {
submitting = false;
}
}
});
Add disabled attribute to your button as the first thing in your js method.
function func(event) {
$("#button").prop("disabled", true);
.....
}
try this it might help for your asp button
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" UseSubmitBehavior="false" OnClientClick="ValidationCode(event); return false;" />
<script>
function ValidationCode()
{
//Code of validtion
event.preventDefault();
if(true)
{
__dopostback:("btnSubmit","");
}
}
</script>
Sample code
Client Side:
$("#submit").click(function () {
if (!YourvalidationFunction)
{
return false;
}
else {
//ajax_function is a folder contain Default.asmx page and insertNewRecord is function name (server side)
$.ajax({
type: "POST",
url: "ajax_function/Default.asmx/insertNewRecord",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessinsertingwcCall,
error: OnErrorCall
});
}
});
Server Side:
[WebMethod]
public string[] insertNewRecord(string prefix)
{
string status = "";
List<string> d = new List<string>();
try
{
// logic code for insertion if success set msg
status = "New record inserted";
}
catch (Exception ac)
{
status = " Error occurs";
}
d.Add(string.Format("{0}", status));
return d.ToArray();
}
i am trying to make an image gallery with pictures fading in and out. I already have that part covered, but so far im hard coding the image url's in my .aspx page. I don't want this, i need it to be dynamic.
<script type="text/javascript">
$(function()
{ var img = $("img.x");
$(img).hide().eq(0).show();
var cnt = img.length
setInterval(imgRotate, 5000);
function imgRotate() {
$(img).eq((img.length++) % cnt).fadeOut("slow",
function() {
$(img).eq((img.length) % cnt).fadeIn("slow");
});
}
});
</script>
<body>
<form id="form1" runat="server">
<div>
<img class="x" alt="Image1" src="Desert.jpg"/>
<img class="x" alt="Image1" src="Lighthouse.jpg"/>
</div>
</form>
this makes the images fade in and out, which is good, but as you can see, i've hardcoded the images in this example. I can't use this for my application.
What i want to do is the following:
i want to pass a List<string> (codebehind) to the jQuery script that will just iterate over the list and replace the source url of the image.
i just want to do something like this in the jQuery script (pseudo-code):
int counter = 0;
var img = ListFromCodeBehind[counter];
//do some fading stuff
count++;
i've tried using <%=%> server tags, and so forth but to no avail. I've read lots of things but they all seem overly complicated for what i'm trying to achieve..
Why is everybody forcing you to use AJAX? There is no need to load image list in separate HTTP request. I assume your code comes from some aspx page. Therefore you can provide a public method in this Pages's class (lets call it GetImages()) that returns a string that looks like JavaScript array. I.e.
public string GetImages()
{
return "['Desert.jpg', 'Lighthouse.jpg']";
}
Then in you JavaScript code (that is placed in this Page's aspx file as well) you can call public method of Page's class with classic ASP syntax:
int counter = 0;
var ListFromCodeBehind = <%= this.GetImages() %>;
var img = ListFromCodeBehind[counter];
//do some fading stuff
count++;
which will finally print:
var ListFromCodeBehind = ['Desert.jpg', 'Lighthouse.jpg'];
and this is the result I believe you expect.
You can add a Web Method into your aspx page (code behind) that can be called by AJAX.
Your code behind method will return a string that contains the URL to the images, in a JSON format (so that JQuery knows how to iterate though it out of the box).
Have a look at this thread to have an idea of how to create a web method in an aspx code behind file. I'd do it via asp.net MVC though...much more straightforward
Calling an ASP.NET server side method via jQuery
//Controller
[HttpGet]
public JsonResult GetImageURLS()
{
var urls = GetUrls();
return Json(new { urls = urls }, JsonRequest.AllowGet);
}
//js file
$.ajax({ url : '/GetImageURLS/', success : function(e) { if (e && e.urls) {
var $images = $(".images");
for (var i in e.urls) {
$images.append('<img src="' + i.url + '" class="x" ' + ' alt="' + i.alt + '" /> ';
}
});
//html
<div class="images">
</div>
Try this for initial load of the images. Then call your function on them after the images are populated.
You can use AJAX and call a webservice in your Javascript to return your image list as follows:
function LoadImages() {
var url;
url = "WebServices/wsImages.asmx/GetImageList"
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function (response) {
var imgList = response.d;
//Loop through image list etc.
}
});
}
I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>