I have a simple C# application that uses a WebView that is loading a small html form that is hosted locally.
The form has two fields, such as: Name and E-mail. It is a button that, when pressed, calls a javascript function that takes all the values of the existing fields in the form, and which must be sent back to C#.
So that later I can save them in the local database or maybe send them to an online server.
var form= $("#formId");
$.ajax({
type: 'POST',
url: 'HOW CAN I SEND BACK TO C#?',
data: form.serialize(),
success: function (data) {
console.log('HOW C# CAN RESPOND BACK?');
}
});
Is it possible for C# to receive this ajax request under the hood? If not, what are the other ways to retrieve these form fields with C# once the user clicks the submit button?
Related
Updated
Since I got your very helpful answers to this question so promptly, I have reconsidered the problem. I think I need to break it down into two small requirements, so I am updating the question.
In my ASP.NET MVC 4 application, I need that when the user presses the enter key on the keyboard while the focus is in a specific textbox:
Scenario 1: The appropriate server side action must be called. If the user presses the enter key when the cursor is in a different text box, another action must be called.
Scenario 2: If the user pressed the Enter key on the keyboard while the focus is in any textbox in one of the forms on the current page, the form must be posted back with all the form data (HttpPost) to the action on the controller as specified in the action attribute of that <form>.
How do I accomplish these two scenarios?
$('#idOfTextbox').keypress(function(e) {
if(e.which == 13) {
$.ajax({
//.. Your values go here...
});
}
});
If you want to intercept a submitted form, you can use the ajaxForm plugin. This way, you can have several forms on the page and when a form is submitted, it will make an AJAX call to the action method specified in the form's action attribute. You will then be able to handle the response in the 'success' callback of the ajax call.
element.onkeydown = function(event) {
//do something on keydown (enter is keyCode === 13)
};
You can use javascript or simply put each input in a different <form> with a button type="submit" inside.
You can do it as below:
$('#idOfTextbox').keypress(function(e) {
if(e.which == 13) {
$.ajax({
url: './savedata',//Your method name, that is to be called
type: 'POST',
contentType: 'application/json',//Type of data you want to post
data: JSON.stringify({ obj: sampleobject }),//object of post-object i.e. data being posted
success: function(result) {
//Logic to handle success
}
error: function(){}//Handle error here
}
});
I have given an example to call a method that is on the same controller on whose view you are currently working with..
I use an Ajax Toolkit modal pop-up extender to pop-up a form for collecting information from the user. I intend to send the data collected from the user to the code behind for saving into the database on click of the submit button on that form. I found out, however, that the submit button is not posting back to the saver at all.
I do not want to use any client side coding or a web service.
Is it in any way possible to do post back on a modal pop?
There are two solutions of your problem:
Create form with asp:button in a div, initially set it's display none. At the time of popup just make it visible you can set it's position as your requirement. Then after click on submit button it will behave normally and redirect your page.
It is by using jQuery and Ajax. Create a html form and on submit call a JavaScript function
JavaScript function :-
function on_submit(){
var pageUrl = 'your_page_name.aspx'
$.ajax({
type: "POST",
url: pageUrl + "/your_web_method",
data: '{data1:value1, data2:value2}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
make your success code here
}
});
in C#
[WebMethod]
public static void your_web_method(data1, data2)
{
// your code to store value in database
}
I have issue in accesing drop down item from c# code behind
Scenario:
i am modifying drop down based on user selection using jquery/ajax call. while accesing the drop down item from code behind, still it retains old list.
Please help to access updated drop down list from c# code behind.
Sample code
Jquery code :
$.ajax({
type: 'POST',
url: "Search.aspx/LoadNewOptions",
contentType: 'application/json;charset=utf-8;',
dataType: "json",
data: "",
success: function (data) {
$("#dropdown").empty();
$($.parseJSON(data.d)).each(function () {
var Option = $('<option />');
xOption.attr('value', this.value).text(this.label);
$('#dropdown').append(Option);
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
C# Code behind code :
dropdown.SelectedItem.Value.Trim() // returns old value
Alternate Solution:
Created separate javascript function and store selected item values in hidden variable. No issues in accessing hidden variables from code behind.
The server has no knowledge of what ensued on the client unless you tell it.
It looks like you are dynamically appending elements to the dropdown. If you rebind the list when the page next executes, it doesn't know that you have modified it on the client.
hidden field is fine for simple situations
you can examine the POST and see if it contains a value which does not exist in the list, and if so, add it
The reason your old value didn't change because the server side has no knowledge of the new value. Unless you post it back to the server it will not be visible.
I have user control which is included in most of my aspx page. This user control shows huge data from database. Now I have decided to fetch that by jquery. I am very much familiar with jquery and how to call server side method by jquery. My problem is that I can not specify ascx file in jquery ajax post method. Like
function loadMore() {
$.ajax({
type: "POST",
url: "Left.ascx/LoadData",
data: "{PageIndex:1}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
I can not call ascx code behind method by jquery because ASCX is not directly served via URL.
I cannot write even C# code for loading & populating ascx from aspx server side method dynamically because it has been used in many aspx. So now I am in problem. No easy & good idea is coming to my mind...so I am stuck. Please show me the way to achieve it. Thanks
You cannot call the ascx method directly. What you have to do is call an aspx page method and from that call the user control method. This sounded familiar so I checked. I have an answer to a similar question here:
Jquery .ajax async postback on C# UserControl
which shows the way this can be done.
It looks to me like you want to get HTML back from your response? Possibly so you can just set the contents of a div instead of having to build the html on the client. If that is the case, then make a new aspx page that contains your ascx and have the ascx databind in the page load of the aspx.
Is there any chance, when I select a row from asp:dropdownlist, dynamically change page, execute sql query and after result, change selected row in second asp:dropdownlist?
If this isn't possible only with asp.net and codebehind, please let me know how to execute SELECT-query in javascript (may be with Ajax; but I don't understand it) and change second dropdown's selected row.
Thanks!
Its a bit of a generic question because there is a couple of options that you could do plus I'm not 100% sure what you want to do. In short you could use AJAX to contact a PHP page which will do an operation on your database. A result it generated and sent back to the client. You could use JSON to hold the data that is getting sent to the browser.
All AJAX does is allow you to get data from another location based on the URI you give. I would use the JQuery library as it makes it easy to implement AJAX.
// This will trigger ajax whenever the is a change in the drop down. I am assuming the drop down class is .dropdown
$('.dropdown').change(function() {
$.ajax({
type: "POST",
url: "page_change.php",
data: { name: "about_us" }
dataType:JSON,
success: function(data) {
//The data returned from test.php is loaded in the .result tag
$('.result').html(data.html);
// If you want to change page you would execute
window.location(data.url);
}
});
});
page_change.php will then contact your database and generate JSON.
More information about JQuery AJAX here:
http://api.jquery.com/jQuery.ajax/
You will need to look at JQuery, AJAX, PHP and JSON to change data on your page.
If you just want to change page on a drop down change I suppose you could store the page name in the option id?
$('.dropdown').change(function() {
var page = $(this).attr('id');
window.location(page + ".html");
});