I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}
Related
I have a grid view where I'm trying to insert a new value. Before doing an insert need to check if the value entered already exists in DB (cannot be duplicate).
The column that needs to be checked for duplicate is of type varchar which can accept maximum characters in a string (it can have spaces and can also have other special characters - it is basically a sentence).
E.g. Insert specific job-related impacts: (for example, impacts to customer or client service)
We cannot make this column unique in SQL server as it is declared as varchar(max).
Can we perform a check for a large string like this from C#?
The primary concept is as follows:
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
int columnToCheck = 0;//The index of the property/field/column you want to check
if (e.ColumnIndex == columnToCheck)
{
using (var DB = new DataContext())
{
if (DB.YourTable.Where(v => v.id == dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()).Count > 0)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
MessageBox.Show("This key already exists");
//Return the error message to your javascript in asp.net here
}
}
}
}
In a website however, you'd have to make an ajax call, so whichever datatable you're using, find its event which would similar to dataGridView's CellValueChanged event. If you fail to do so, try adding the onchanged="" tag to its HTML element definition e.g. <table class="table" id="tab" onchanged="eventfunction(this)"></table> and in your javascript, handle the call like the following:
function eventfunction(element)
{
//Use an ajax call to your controller from here
var id = document.getElementById(element.id).innerText; //or however you can obtain the active cells' value
$.ajax({
url: "/api/ControllerName/ActionName",
method: "POST",
data: id,
success: function (response)
{
//Handle the return call here
},
error: function (response)
{
//Or here if you return an error message
}
});
}
Or you can use jQuery's event handling like this:
$("#tab").on("onchange", function()
{
//Your code here
});
You controller can look like this:
[HttpPost]
public Customer GetCustomer(string id)
{
//LINQ Where validation here
}
I looked around in several forums for an answer to my problem, but I only found the solution in combination with a button.
I have to "translate" a website from Javascript to C# ASP because I have to store data in a SQL DB.
Now, I had a validation routine were the entries were checked before the data as sent by mail (that was in the old website, now it should be stored). One of the checks was only a warning (confirm) and not an error (alert). In JavaScript I did this with:
if (a > b){
Check = confirm("Are you sure your entry is correct?");;
if (Check == false){
return false;
}
}
Since I have many more checks before and after this part, I can't hook it to a button.
Is there a way to solve it like the alert? e. g.
<script type = "text/javascript" language = "javascript">
<asp:Literal id="ltlAlert" runat="server" EnableViewState="False"> </asp:Literal>
</script>
private void Say(string Message)
{
// Format string properly
Message = Message.Replace("'", "\\'");
Message = Message.Replace(Convert.ToChar(10).ToString(), "\\n");
Message = Message.Replace(Convert.ToChar(13).ToString(), "");
//Display as JavaScript alert (!)
ltlAlert.Text = "alert('" + Message + "')";
}
like:
private bool Ask(string Message)
{
// Code to display confirm from Javascript here
return;
}
I'm pretty new to C# (otherwise I programmed in VB, VBA and - Long ago - in COBOL) so I'm still trying to get my bearings.
Are you looking for something like the following where you can check several conditions before submitting a form? The button would call that JavaScript function.
function ValidateForm(){
if(email is invalid){
alert("Email is invalid");
return;
}
if(phone is invalid){
alert("phone is invalid");
return;
}
var Check = confirm("Are you sure your entry is correct?");
if (Check == false){
return false;
}
else{ Submit Form };
}
I have a function named "callfunction()" in JavaScript(Mypage.aspx) .This function should call another function "func()" in C# (Mypage.aspx.cs )
Something like this:
(in Mypage.aspx)
function callfunction()
{
// i have to call func() function here .....
}
</script>
(in Mypage.aspx.cs file)
public void func()
{
// My code goes here
}
I have researched alot because of this and i ended up so far with 2 conclusions:
1st was to use Json, but my superiors said clearly that they dont want me to do so.
2nd was that i cant do as i wish because of the client, server aspnet protocol
Please give me any kind of tip in how to do this, i am getting desperate
Ok....Try using page methods
First add a script manager on your aspx page
<asp:ScriptManager ID="scpt" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Then go to your aspx.cs page and declare a function something like
[System.Web.Services.WebMethod]
public static string ValidateUser(string emailId, string password)
{
//Your logic code
return returnString;
}
Then from your javascript call the c# method like
PageMethods.ValidateUser(email, password, CallSuccess_Login, CallFailed_Login);
And also in ur javascript create 2 call back functions CallSuccess_Login and CallFailed_Login
Hope it helps
If it's a webforms project (not MVC) and you don't want to use AJAX, you can use __doPostBack.
<script type="text/javascript">
function callfunction(parameter)
{
__doPostBack('func', parameter)
}
</script>
C#:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
var senderObject = Request["__EVENTTARGET"]; // func
if(senderObject == "func")
{
//call your function here, or write the implementation
}
}
below are the options available to you
If your using asp.net then use Ajax tools to create this
if you don’t want to user Ajax toolkit use JavaScript __doPostBack
or other option write server side function in the web service and call web method using JavaScript
I'm new to integrating JavaScript into a web site, but I'm going to need it often in my web site.
Here is an example:
Assuming I have the function:
showAlert()
Say I have:
<div id="some_div">
</div>
Could someone provide me some kind of example that would do this:
If I have a button and the user clicks it, this should raise an event in the backend and call some method in my C# file. Then my C# file should be able to call some other javascript method of the front end which would call showAlert() and display the alert in the div.
This is what I can't seem to find any information on.
The basic idea of passing information to and from the server. Any help with this would be really appreciated.
Thanks
Your best bet is to use a framework like jquery, then bind to the button, call the service, and handle the response. The below is a quick example of this.
$(document).ready(function()
$('#Button1').bind('click', function () {
// This grabs the page you are in so that you can call it correctly
var pagePath = window.location.pathname;
var testId = $("#some_div").val();
var url = pagePath + "/TestService";
$.post(url, { id: testId },
function (data) {
showAlert(data);
}
});
};
});
First, you need to make sure the document is ready at some point. Bind allows the the button to be bound when the document loads. Then, by clicking it, you execute the anonymous function that grabs the testId, calls your service, and handles the data response in a success callback.
Hope that gets you started in the right direction!
EDIT: Added backend webforms "service" exposure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestService(string id)
{
var string = DBCollection.FirstOrDefault(x => x.id == id); // Or whatever you want to return the data
return "You called me on " + DateTime.Now.ToString() + "with " + string;
}
}
This would allow you to call the "WebMethod exposed on your page. For more help with this, please see the following link.
http://www.tugberkugurlu.com/archive/asp-net-web-forms---calling-web-service-page-methods-using-jquery
EDIT: Additional Considerations when performing this type of approach in webforms.
Calling a webmethod with jquery in asp.net webforms
I want to search a database for a clientName and dynamically show the results while the user is typing so they can select a User. It is now my understanding that this cannot be done without using javascript.
So if the user is typing "Al" then reults of clients called "Allan, Alison, Ali..." etc would show in a dropdownlist like display under it.
At the moment the user is entering the Clients name into a Textbox.
I know that creating the DropDownList should be done something like this:
private void InitializeNameDropDown(DataTable dtTable)
{
string ClientName = Clienttb.Text;
MySqlDataReader Reader = MySQLQuery(ClientName);
int nTotalRecords = dtTable.Rows.Count;
for (int i = 0; i < nTotalRecords; i++)
{
NameDropDown.Items.Add(dtTable.Rows[i]["Client"].ToString());
}
}
MySQLQuery() just checks that the client exists within the database.
But I don't know how to dynamically interact with the database to return the results as the user is typing.
Any Help will be appreciated, Thank you in advance.
You can do it without JS, hang event on text change on TextBox (OnTextChanged), and in there update DDL ( dont forget to set AutoPostBack=true ).
But it can easily make user wait ( "freeze page" ), or even rollback what he wrote if you are using Ajax.NET
I strongly recommend using JS rather then this ( use JS and WCF/ashx/regular WS, any of these will do ) due to performance gain and much better possibilities of customization.
ASP anyway generates a load of JS for "ASP controls".
This can be applied for example http://www.codeproject.com/KB/aspnet/Cross_Domain_Call.aspx
You'll have to hook into the keyup event on the text box and fire an XmlHttpRequest from that event - if you're using jQuery it's pretty simple:
$('#mytextbox').keyup(function() { $.ajax(blah blah) });
Alternatively, as Dennis says, just use the auto-complete plugin - it's very simple and works well.
As for the client side try jquery and jqueryui's autocomplete, it's just a suggestion, jquery has a nice ajax call and it's really simple to use, and for the jqueryui autocomplete, you just pass it keywords and it will create a list right under the input box.
http://jquery.com/
http://jqueryui.com/
http://api.jquery.com/jQuery.ajax/
Here's some code that might get you going.
It uses the jquery Javascript library. It assumes you're getting the full HTML of the results list that you want to display to the user. You'll need more Javascript to dynamically show/hide the box that contains the list. You'll also need a server-side script that gets a collection of search results based on some search text. That script should be located at the URL defined in the #searchPartialUrl tag (which can be hidden). The search text should be in an input called #searchText.
I like this method because you can maintain your JS code in a separate file and reuse it. Your server just needs to create HTML views that have all the async target information in regular HTML tags.
I also implemented a delay between checking key-events so that you're not constantly sending requests to your server. (I got this method from another answer on stackoverflow, but I can't seem to find it now. I'll give credit when I do.)
// This function is used to delay the async request of search results
// so we're not constantly sending requests.
var mydelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
var asyncSearchForm = function(onSuccess) {
var keyupWrapper = function(keyCode) {
// if this key was an arrow key, then
// ignore the press
for (var i = 37; i <= 40; i++)
if (keyCode == i)
return;
// get all the search info from the form
var searchText = $('#searchText').val();
var searchPartialUrl = $('#searchPartialUrl').val();
// make the ajax call
$.ajax({
type: "POST",
url: searchPartialUrl,
data: {
searchText: searchText
},
dataType: "html",
// on success, the entire results content should be replaced
// by the results returned
success: function(data, textStatus, jqXHR) {
$('#searchResults').html(data);
onSuccess();
},
// on error, replace the results with an error message
error: function(jqXHR, textStatus, errorThrown) {
$('#searchResults').html('<p>An error occurred while getting the search results.</p>');
}
});
};
onSuccess = (typeof (onSuccess) == 'undefined') ? function() { } : onSuccess;
// On each key-up event, we'll search for the given input. This event
// will only get triggered according to the delay given, so it isn't
// called constantly (which wouldn't be a good idea).
$('#searchText').keyup(function(e) {
// delay between each event
mydelay(function() {
// call key up
keyupWrapper(e.keyCode);
}, 500);
});
}
Update:
You said you're using C#. If you're using MVC, you'll need an action in your controller to be a target for your async request. Here's an example:
[HttpPost]
public ActionResult GetSearchResults(string searchText)
{
// Here, you should query your database for results based
// on the given search text. Then, you can create a view
// using those results and send it back to the client.
var model = GetSearchResultsModel(searchText);
return View(model);
}