I am trying to call a JavaScript function on click in a MVC2 View Page.
<a onclick=" SelectBenefit(<%=o.ba_Object_id %>,<%=o.ba_Object_Code %>)" href="#">Select</a>
JavaScript function
function SelectBenefit(id,code) {
alert(id);
alert(code);
}
Here ba_Object_Id and Code are the values from the ViewModel. If I use SelectBenefit(<%=o.ba_Object_id %>) in this way, its working fine. But when I have two paramaters its not.I am getting this error:
conditional compilation is turned off.
I think that you need to put quotes around the second parameter if it is a string:
<a onclick=" SelectBenefit(<%=o.ba_Object_id %>, '<%=o.ba_Object_Code %>')" href="#">Select</a>
This being said your parameters need to be properly encoded and I wouldn't pass them likse this. I would serialize them as JSON object to ensure that everything is OK. Like this:
<a onclick="SelectBenefit(<%= new JavaScriptSerializer().Serialize(new { id = o.ba_Object_id, code = o.ba_Object_Code }) %>)" href="#">Select</a>
and then the SelectBenefit function might look like this:
function SelectBenefit(benefit) {
alert(benefit.id);
alert(benefit.code);
}
I'm guessing o.ba_Object_Code is not a number? Try putting quotes around it:
<a onclick="SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>')" href="#">Select</a>
You could also write this function like this:
Select
Or use Jquery (best approach, imo):
$('#yourlinkid').click(function(){
SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>');
return false;
});
Related
I want my C# code to get the currently-selected option from an HTML5 dropdown list. Our situation is perhaps a bit different from many others, since this is not a client-server web app, but rather a desktop app which uses HTML for its UI in order to be more portable to Linux. To support this, we use an embedded Firefox browser with the Gecko engine.
I'm new to working with HTML using C#, and I can't seem to find the right API call for this.
The HTML looks like this:
...
<div class="select">
<select id="ddlMyOptions" name="ddlMyOptions">
<option></option>
<option>first choice</option>
<option>second choice</option>
</select>
</div>
...
And the C# code I'm using to try to access it is:
IHTMLElement selectElement = documentHTML.GetElementByID("ddlMyOptions");
string value = selectElement.Items[selectElement.SelectedIndex].Value;
string text = selectElement.Items[selectElement.SelectedIndex].Text;
This is based on examples I have seen from other posts, but those posts are using asp.net and in my case Items and SelectedIndex are not defined for selectElement.
Also, I have seen some posts about using Javascript, but I would prefer to keep this all in C#, if possible.
I looked at what it would take to have a callback method on the dropdown, so I could get the selected value whenever it changed and save it to an instance variable in my class, but I wasn't able to figure out how to specify the callback method, either.
Any help would be highly appreciated!
Since there were no answers to my question, I went ahead with a JavaScript solution:
function updateDDLSelection(elid) {
var el = document.getElementById(""ddlMyOptions"");
var val = el.options[el.selectedIndex].value;
el.setAttribute('value', val);
}
Then, I had to change the HTML from what was shown above to this:
...
<div class="select">
<select id="ddlMyOptions" name="ddlMyOptions" onchange=""updateDDLSelection(event)"">
<option></option>
<option>first choice</option>
<option>second choice</option>
</select>
</div>
...
And here's the revised C# code to get the value that was set by the JavaScript function:
IHTMLElement selectElement = documentHTML.GetElementByID("ddlMyOptions");
string value = selectElement.GetAttribute("value", 0).ToString();
Hope this is helpful to someone else who is in a similar situation...
I am trying to get strings that I have put in my session variables to another aspx webform. I am getting it inside my JS script and I would like to know how to go about it. I have tried the following but it doesnt seem to work. Please anyone guide me a bit.
Home.aspx.cs
HttpContext.Current.Session["InstitutionID"] = BankID;
HttpContext.Current.Session["InstitutionName"] = txtBankName.Text.Trim();
Index.aspx
$(document).ready(function () {
var param1var ='<%= Session["InstitutionID"]%>';
var param2var = '<%= Session["InstitutionName"]%>';
console.log('param1', param1var);
console.log('param1', param2var);
........
})
Are you using System.Web.SessionState.HttpSessionState.Session object to get the session object data in the Javascript? That is how I use it in one of my WebForms projects. Hope it helps.
HttpContext.Current.Session[Constants.SessionStateVariables.LoginFailed] = false;
var loginIsFailed = '<%=Session[XYZProcet.Common.Constants.SessionStateVariables.LoginFailed]%>';
after long surfing via google I hope somebody can give good answer.
Here I have some javascript with I get in .NET C#
<script type="text/javascript">
var itemMap = new Array();
itemMap[0] = {
pid: "20466846",
sku: 13897265,
sDesc: "XSMALL",
sId: "101979",
cDesc: "Black",
cId: "1203740",
avail: "IN_STOCK",
price: "$4.99",
jdaStyle: "60016655"
};
How can I get results from this string in .NET that I can work with it?
I tried to use JINT (http://jint.codeplex.com/) but when I run script it's return for me type of object and I can not do anything with that...
I need with out some changes in javascript source get data. It's not JSON obj so I can not parse it.
Any suggestions?
Thanks
If you have an appropriately formed JSON object stored in the clip board (which I'm guessing is the transport that you'll be using to send to your back-end), you can create an object via Paste Special under the edit menu that will generate the appropriate class in .NET to hold that object, e.g.
This also works for XML objects.
You can save these values into hidden fields
<script type="text/javascript">
var hiddenField1 = document.getElementById('hiddenField1');
hiddenField1.value = ???;
</script>
<asp:HiddenField runat="server" ID="hiddenField1" Value="" ClientIDMode="Static" />
and in codebehind file you can access the hidden field by
hiddenField1.Value;
What is the recommended way to handle "Nick / Email taken" AJAX validation in MVC that integrates nicely with validators provided by DataAnnotantion (#Html.ValidationMessageFor(model => model.Email))? I understand that I would probably have something like this:
<input id="email" onBlur="emailTaken();" onchanged="emailTaken();" />
<script type="text/javascript">
function emailTaken() {
var encodedEmail = enc($("#email").val());
$.getJSON("/Ajax/EmailTaken/" + encodedEmail, function (data) {
if (data.res) {
// all is OK
} else {
// TODO: Show Error?
}
});
}
</script>
I already know that on Server I can do ModelState.AddModelError and I am doing it... but I want to know what is recommended way for ClientSide validation? Do I need to invoke some method provided by jquery.validate.unobtrusive.js?
You would probably want to use Remote Validation for this. It's built-in, so you don't have to do any of your own javascript.
http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
I already found this on this website.
how to pass session variable in href
But what I want is vice versa. and I can't get it done..
I need some correct syntax..
is it ......
..../home.aspx?<%Session["egSession"]=1%>
or
..../home.aspx?=<%Session["egSession"]=1%>
or
..../home.aspx?<%=Session["egSession"]=1%>
But i believe all of the above are wrong.. coz none of them are working..
Tkz..
Session.Add("egSession", 1) will add 1 to the session cookie egSession.
You could also probably be sure it doesn't already exist by doing so:
Session.Remove("egSession");
Session.Add("egSession", 1);
To get the querystring value from the address you would (code behind do)
var value = Request["egSession"];
So that means you could do:
Session.Remove("egSession");
Session.Add("egSession", Request["egSession"]);
Hope that helps!
** UPDATE **
If you can't touch the .cs files, you can do this in the ASPX-file, by wrapping your code in <% ... code goes here ... %>
if the new session variable value is know, e.g. 1 in your sample setting it can be done anywhere
<% Session["egSession"]=1; %>
if you want to pass it through as a query parameter do this:
..../home.aspx?egSession=<%=Session["egSession"]%>
The point is, you need a name for the value, i.e. egSession but you may call it what ever you want.
However, if you alldready know the value you can simply do:
..../home.aspx?egSession=1
From what I am understanding you want something like this:
APage
Take Me home
Home.aspx.cs: the code behind page, in say the OnPageLoad Event
Session["egSession"] = Request.QueryString["egSession"];
Home.aspx
<div>Session: <% =Session["egSession"] %></div>
<div>Query String: <% = Request.QueryString["egSession"] %></div>
If you are trying to to it all in one I would try the following:
APage.aspx.cs
Create a public method (change the type of the input parameter if needed)
public string SessionMagic(object input)
{
Session["egSession"] = input;
return Session["egSession"].ToString();
}
APage.aspx
A Link
*UPDATE: *
If you can not update the .cs files you can add server side code in the aspx page, not great practice but it can be done. Encapsulate the code in script tags with the run a server attribute set. E.g.:
<script runat="server">
public string ServerSideFunction(string input)
{
Session["egSession"] = Request.QueryString["egSession"];
public string SessionMagic(object input)
{
Session["egSession"] = input;
return Session["egSession"].ToString();
}
}
</script>
you can use javascript with cookie to store the value that you want to set into Session.
eg:- url- url.apsx/egValue=1 read this url using javascript. Put the key and value into cookie.
Then you can read cookie value from server and put it into session.
hope it helps.