ajaxToolKit autoCompleteExtender OnClientItemSelected - javascript

I am trying to implement an autoCompleteExtender into my project. Currently I am using the OnClientItemSelected property to call a javascript on the client side. Is there a way (using another property or some other code) that will let me call a method in the code behind when the user selects an option?

function AutoCompleteEx_OnClientItemSelected(sender, args) {
__doPostBack(sender.get_element().name, '');
}
On server side handle TextChanged event of extended textbox.

For this you need to return the list from web service method with ID and Text
Here "lst" is the actual list with data from your data source.
List<string> items = new List<string>(count);
for (int i = 0; i < lst.Count; i++)
{
string str =AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(lst[i].Text,Convert.ToString(lst[i].IDValue));
items.Add(str);
}
return items.ToArray();
Then simple javascript
function GetID(source, eventArgs )
{
var HdnKey = eventArgs.get_value();
document.getElementById('<%=hdnID.ClientID %>').value = HdnKey;
}
and dont forget to set the attribute in auto complete extender
OnClientItemSelected="GetID"

Related

Calling a controller function from onchange event in html view

I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this: "Jul 2017". There can be as many as 12 entries in the list.
When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.
How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.
I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.
Html View Code
#Html.DropDownList("selectList", Model.ReverseMonthsLists())
View Model Code
public IEnumerable<SelectListItem> ReverseMonthsLists()
{
var selectListItems = GetDates()
.Select(_ => _.ToString("MMM yyyy"))
.Select((dateString, index) => new SelectListItem
{ Selected = index == 0, Text = dateString, Value = dateString })
.ToList();
return selectListItems;
}
public static IEnumerable<DateTime> GetDates()
{
DateTime startDate = new DateTime(2017, 6, 1).Date;
var currentDate = DateTime.Now.Date;
int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
currentDate.Month - startDate.Month;
var dates = new List<DateTime>(numberOfMonthsToShow);
currentDate = currentDate.AddMonths(-1);
for (int i = 0; i < numberOfMonthsToShow; i++)
{
dates.Add(currentDate);
currentDate = currentDate.AddMonths(-1);
}
return dates;
}
Controller function
public ActionResult Report_Performance()
{
//var newDate = DateTime.Parse(strDate); //<- Use newDate as parameter value into aVar to replace date at the end of the string
var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
return this.View(aVar);
}
The normal way to get a value to a controller is for the user to post the page back to the server, e.g. via a submit button. When this happens, the controller's action method can receive the selected item as an argument and then do what it needs to do. So if you just want the user to submit the form, and allow the web site to render the next page based on the selected value (and a list that you compute based on that value), that is all you need to do.
On the other hand, perhaps you don't want the user to submit the page; you want a series of dates to be displayed within the page, or for the dates to be processed by code running in the browser. If that is the case, I would suggest you perform the computations in Javascript within the browser itself, thereby avoiding the need for a round trip. Nothing in your GetDates() method requires any server side data, so it's just a question of converting your c# code to Javascript code.
In some rare cases, you will want a UX element on the page to get updated immediately based on a server computation, without the page being posted. If that is what you want, you'll have to use the AJAX solutions the other posters have provided. It's much more complicated and much more work. If you don't need that, use one of the solutions I provided above.
You Can Use The OnChange EventHandler For The HTML Select Option
(The DropDownList ) To Start An Ajax Call To Your Controller , Simply Create a JavaScript Function That Preforms a Jquery Ajax Request Containing The User Selected Data To The Controller and Retrieve JSON From The Controller Using Return Json() Instead Of Return View() , Then Handle The Retrieved Data Using JavaScript , Your Controller Will Need To Accept a Parameter In Order To Receive The Data From The Ajax Request
function SendDataToController (TheDropDownName){
var DataToSend = $('#'+TheDropDownName).text();
// Or Pass `this` From The Html When Assigning The Event Listener
// and Do Something Like var DataToSend = this.text();
$.ajax({
url: "#(Url.Action("ActionName", "ControllerName"))",
data: DataToSend,
success: function(ResponseFromController){
//Do Stuff With Response
}
});
}
This Will Send The Data To Controller So You Should Receive It in A Parameter
public ActionResult MyAction (string DataToSend)
{
//Do Stuff With Data and Get a Json Object To Return
Return Json(JsonObject);
}
MVC Ajax Is Essential So You Should Learn It Before Tryin To Work On Any MVC Project, Also You Should Handle Request Error Using fail attr in The Ajax Setting But I Will Leave That To You

Need to force post back from Javascript not initiated by a button click

I need to use a JavaScript Confirm function in my ASPX pages to confirm various actions based on conditions in the C# code behind not directly connected to a button click event. E.g. if it is calculated that number of records > 200, ask 'Do you want to continue?' then based on Yes or No clicked perform relevant actions.
I have my JavaScript defined as:
<script type = "text/javascript">
function Confirm(val) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(val)) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
And call it from code behind and get the response using RegisterStartupScript and Request.Form like so:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "confirm_value", String.Format("Confirm('{0}');", msgstr), true);
string confirmvalue = Request.Form["confirm_value"];
The Confirm box comes up, but the confirmvalue string is always "behind". That is, if I click 'Yes' on the Confirm box, it returns 'No'; but if I stay on the same page and execute the process a second time and click 'No', I get 'Yes' returned; and so on.
Question: How do I force postback of confirmvalue so I can access the response in code behind in a timely manner?
There can possibly be four ways by which you can achieve this with/without post back:-
Using AjaxMethod Attribute on a method in a code-behind file as below:-
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public object DoSomething(int countValue)
{
//Do Something
}
Then from the ascx file you will be able to call the method by executing the class name dot the method name. Here, in this case the method name is DoSomething.
In case you are using ScriptManager in your ascx file then you can enable page methods invocation by setting EnablePageMethods attribute of the Script Manager as true. But, the method you are invoking should be static. MSDN link
public static object DoSomething(int countValue)
{
//Do Something
}
Here, you will be able to call the method directly from your JS.
Using web service as follow:-
[ScriptService]
public class YourService
{
[WebMethod(EnableSession=true)]
public object DoSomething(int countValue)
{
//Do Something
}
}
Post back way:-
if (IsPostBack)
{
string ControlID = string.Empty;
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
ControlID = Request.Form["__EVENTTARGET"];
Control postbackControl = Page.FindControl(ControlID);
}
}

How to send a value from client side to server side for server side processing

I am trying to send a value from the client side using javascript or JQuery, to the server (ideally to a method in my codebehind). I am using C# .net 4.0.
In my client side JQuery I have:
$.post("test.aspx/testMethod",
{
name: "Donald Duck",
city: "Duckburg"
}
);
In my server side (test.aspx.cs) method, I have
public void testMethod()
{
string name = Request.Form("name");
string city = Request.Form("city");
}
But with this I get a compilation error: "Non-invocable member 'System.Web.HttpRequest.Form' cannot be used like a method."
How can I rectify this? Or reach the same objective? Using the $.ajax({...}) is not an option as the value is needed by a non-static method.
There is a very simple answer to this. After searching for hours thru dozens of questions posted along the same lines and many people offering overly complicated ajax post back solutions, I came up with this. Basically a one liner. Hope it helps someone:
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
you can use like this - https://rvieiraweb.wordpress.com/2013/01/21/consuming-webservice-net-json-using-jquery/
try it :)
I dont know if Web Forms support this type of JSON request. I have tried long back but I have to add asmx file that time. Currently you have WCF, but if you don't want to change your webforms project and still want restful api, then merge MVC project for your restful task. You dont have to shift everything but it work together. Here it is explained how?
I don't know about latest version of Web Forms but before VS2012, you can't do ajax type call to page. As far as I know.
Please let me know if any further details needed.
Found Solution... (Hope someone finds it useful)
JAVA SCRIPT
function myFunction() {
var str= "fname=Henry&lname=Ford";
log("MyString=" + str);
}
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "Default.aspx", true); // Default.aspx being the page being posted to
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(message);
}
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
string code = HttpContext.Current.Request.Form["MyString"];
// code = "fname=Henry"
// For looping etc, see below
}
}
WHAT ELSE YOU CAN GET....
HttpContext.Current.Request.Form.Count // 2
HttpContext.Current.Request.Form.Keys.Count // 2
HttpContext.Current.Request.Form.AllKeys[0] // "MyString"
HttpContext.Current.Request.Form.Keys[0] // "MyString"
HttpContext.Current.Request.Form.AllKeys[1] // "lname"
HttpContext.Current.Request.Form.Keys[1] // "lname"
HttpContext.Current.Request.Form[0] // "fname=Henry"
HttpContext.Current.Request.Form[1] // "Ford"
Loop through keys...
foreach (string key in Request.Form.Keys)
{
DoSomething(Request.Form[key]);
}
The above code works in that it passes a value(s) from the client side javascript to the server side code-behind, but then unable to use the value because you lose it.
The following modification to the above code is required to use the value (essentially store it in a separate static class until needed).
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
// Reset staticValue
Class1.staticValue = "";
Class1.staticValue = HttpContext.Current.Request.Form["MyString"];
// Call Class1.staticValue anywhere else and you get expected answer= "fname=Henry"
}
}
STATIC CLASS (App_Code/Class1.cs) - another object to store value (otherwise the HttpContext object removes it from anything)
public class Class1
{
private static string myValue = "";
public Class1()
{
//
// TODO: Add constructor logic here
//
}
public static string staticValue
{
get
{
return myValue;
}
set
{
myValue = value;
}
}
}

How do you set a session variable in JavaScript?

Can this be done with a PageMethods call? I need to save some variables in a control so that they can be used by a control on another page at a later time. Is there a way to do this via JavaScript?
Sounds like you need cookies, localStorage, or sessionStorage.
You can use JS to change the values in a hidden field, and capture them on the postback, which personally I think preferable to cookie usage if the value is only needed for the life of the current session.
It's a very bad idea to do this with PageMethods.
You can add a generic handler (*.ashx) and then do a XMLhttpRequest to this URL, passing it parameters.
Note that the ashx handler needs to inherit from IRequiresSessionState, in order to access a session.
You can also get a session value that way.
Like this:
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler , IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string item = context.Request.QueryString["item"] ?? "";
string update = context.Request.QueryString["update"] ?? "";
switch (item)
{
case "A":
if (!string.IsNullOrEmpty(update))
context.Session["A"] = update
object a = context.Session["A"];
context.Response.Write(a != null ? (string) a : "none");
break;
case "B":
if (!string.IsNullOrEmpty(update))
context.Session["B"] = update
object b = context.Session["B"];
context.Response.Write(b != null ? (string) b : "none");
break;
}
}
public bool IsReusable
{
get { return false; }
}
}
See my post here for XMLhttpRequest:
Why does this JavaScript code ignore the timeout?
You might want to add a parameter no_cache=TIME_IN_MILLISECONDS, in order to beat browser caching.
I like to do it the following way:
javascript:
function SendData(data) {
var postbackarg = "#####" + data;
__doPostBack("txtTest", postbackarg);
}
VB In Page_Load event:
If Me.IsPostBack Then
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim args As String = Request.Params.Get("__EVENTARGUMENT")
ProcessUserInterfaceData(controlName, args)
If (controlName = "txtTest" AndAlso args.IndexOf("#####") = 0) Then
args = args.Substring(5, args.Length - 5)
'args now = data from the UI
End If
End If
This started from an example I found somewhere else. I cannot find it.. The only purpose for the 5 '#' is to identify the postback as coming from SendData.
Session variables cannot be set using Javascript directly
But you can use the following code to set session variables in aspx page
<%Session["SESSION VARIABLE NAME"] ="SOME STRING"; %>
You can check the same variable using an alert in javascript
alert('<%=Session["SESSION VARIABLE NAME"] %>');
Yes session variable can be set using Pagemethods using the below way
declare the below code in aspx.cs page
[WebMethod]
public static void functionname(string st)
{
Home h = new Home();
System.Web.HttpContext.Current.Session["SessionUserName"] = st;
h.strUserName = (string)System.Web.HttpContext.Current.Session["SessionUserName"];
}
and call the function using pagemethod in aspx
PageMethods.functionname("HELLO");
this will set the session variable to HELLO
You can also make an ajax call to the webmethod if you dont want to use pagemethods.function!!

Is it possible to execute Server side code before executing client side code in ASP.Net

I have a Link button in DataGrid for to edit the grid data, I'm using OnClientClick event for loading a modal form and also i'm using onSelectedIndexChanged event function of the GRID for loading editing data to to controls. see the server side code below
protected void GetSelectedData(Object src, EventArgs e)
{
String Team_Id = GridView1.DataKeys[GridView1.SelectedIndex].ToString();
using (MySqlConnection DbConnection = new MySqlConnection(ConfigurationManager.AppSettings["ConnectionStr"]))
{
DbConnection.Close();
string cmdText = "SELECT Team_Id,Team_code,Team_Name FROM Team_Details WHERE Team_Id=?Id";
MySqlCommand cmd = new MySqlCommand(cmdText, DbConnection);
cmd.Parameters.Add("?Id", MySqlDbType.Int32).Value = Convert.ToInt32(Team_Id);
DbConnection.Open();
MySqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
this.txtTeamCode.Text = DR.GetValue(1).ToString();
this.txtTeamName.Text = DR.GetValue(2).ToString();
}
}
}
see the Client side code for invoking the modal window,
function EditDialog(){
$('#newTeam').dialog("open");
alert(document.Team.txtTeamCode.value);
document.getElementById("cvCode").innerHTML = '';
document.Team.txtTeamCode.focus();
}
The problem is, while poping up the modal form, the fields (team code & team name) are getting blank. Please provide a solution to solve this issue.
You could use an AJAX request to populate the modal pop-up's fields - call an object/service that would return the required data items and then modify the GUI accordingly.
Take a look at JQuery's get() function. For usability it's probably best to do this asynchronously.
Here's a decent tutorial that offers a possible implementation.
HTH
You can make use of httphandlers or as the prev user mentioned make ajax calls.
You can also make use of Pagemethods to call the server side code from javascript.

Categories

Resources