Using jQuery to get DDL selected value inside nested listview - c#

I have a nested ASP.NET ListView, the outer one presenting groups of questions, and the inner one presenting distinct questions within the group. Some of the questions are presented as drop down lists. I want to detect the selected value on change without doing a postback. I have seen lots of references that look like "$(#control).val()" but I need a bit more flexibility.
I am adding the JavaScript in the C# code and it looks like this:
js = string.Format("javaScript:setInputSelectOption('{0}'); return false;", hidSelector.Value);
ddlInputSelectOptions.Attributes.Add("onchange", js);
The resultant aspx file contains this generated code;
<div id='Management_q2'>
<input type="hidden" name="ctl00$body$lstExecutive$ctrl1$hidSelector" id="ctl00_body_lstExecutive_ctrl1_hidSelector" value="Management" />
<select name="ctl00$body$lstExecutive$ctrl1$ddlInputSelectOptions"
id="ctl00_body_lstExecutive_ctrl1_ddlInputSelectOptions"
onchange="javaScript:setInputSelectOption('Management'); return false;">
<option value="0">Not Present</option>
<option selected="selected" value="1">Occasionally</option>
<option value="2">Customarily and Regularly</option>
<option value="3">Constantly</option>
</select>
</div>
My .js file contains this code:
function setInputSelectOption(question) {
var n = $('[id$=' + question + '_q2]>[id$=hidSelector]').val();
var v = $('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]');
setDDLData(n, v);
}
Using Chrome, I have tried these variants on the "var v = " line with the corresponding results:
$('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]'):
d.fn.d.init[1] $('[id$=' + question +
'_q2]>[id$=ddlInputSelectOptions]').value: undefined $('[id$=' +
question + '_q2]>[id$=ddlInputSelectOptions]').val(): ""
So I am (yet again) looking for the right incantion to utter to jQuery so that it will return the selected value from the DDL.

I would suggest keeping it simple. Add a data- attribute to the DDL you wish to get the values from. Use jQuery to find the value.
ddl.Attributes.Add("data-ddl","reference");
Then in JS.
// get value
var ddlValue = $("select[data-ddl='reference']").val();
// assign value
$("select[data-ddl='reference']").val("option");
Also, if the JS is only for UI logic, it's best to keep it out of the C# code and run it on the page ready using jQuery. So in your JS file.
$(function(){
// bind a function to the select change event
$("select[data-ddl='reference']").change(function(){
// insert UI logic here
});
});

Related

How can I get the selected value from a dropdown from within a razor file in ASP.NET Core MVC

Let's say I have a view Foo.cshtml like this:
<form method="post" action="/">
<select id="Country" name="Country">
<option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
</select>
<button type="submit">Register</button>
</form>
#{
string selectedValue = ???;
string selectedText = ???;
}
How could I go about initializing these strings?
I think there is a misunderstanding over server side and client side in your code
lines below are rendered and paraphrased by server
#{
string selectedValue = ???;
string selectedText = ???;
}
it means when it reached to the browser,its done and cannot be changed
If you want to have selected value in dropdown,you should be using javascript to get what you want not server side language
you can use javascript
var e = document.getElementById("Country");
var value= e.options[e.selectedIndex].value;
var text= e.options[e.selectedIndex].text;
or get it via jquery
$('#Country :selected').text();
$('#Country :selected').val();
if I understood you correctly, you want to get the selected dropdown and pass it on to the variable below, well you could use could use javascript like so:
<form method="post" action="/">
<select id="Country" name="Country">
<option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
</select>
<button type="submit">Register</button>
</form>
var getCountry = document.getElementById("Country");
var selectedValue = getCountry.options[getCountry.selectedIndex].value;
The code below only executes once at page load to assist in rendering the HTML for your view. This is true for any C# you have in your cshtml files.
#{
string selectedValue = ???;
string selectedText = ???;
}
As other answers have noted, the way to dynamically retrieve the value of any input control is with JavaScript.
I'm assuming that after you've retrieve the selected value and text from the drop down that you'll want to use it for something in the partial view?
In which case, you'll need to use JavaScript for that as well.
//retrieve your values
var e = document.getElementById("Country");
var value= e.options[e.selectedIndex].value;
var text= e.options[e.selectedIndex].text;
//use them to do something
var targetElement = document.getElementById("your-target-elements-id");
targetElement.innerHtml = 'Text:' + text + ' Value:' + value;

Populate dropdownlist from a value

I have a drop down list which contains 3 values:
Male
Female
Unspecified
Basically in my view, when I selected with male, female or unspecified, I want to change the data that I have in another combo box, e.g. the male users, the female users and the users who haven't given their gender.
List<User> users = new List<User>();
foreach (User user in ctspc.db.AllUsers.ToList())
{
users.Add(DAL.Getusers(user.UserId));
}
So here I get all the users, my problem is I need to use LINQ to sort out which type of gender I need to search, that bit I can handle, the problem I am having is that I am unable to retrieve the drop down list value.
I tried:
var x = Request.Params["cboGender"];
But I assume because the page hasn't loaded yet, it isn't able to get what the current value is, so basically what I am trying to do is have it so depending on the value in the list box at the time, I want it to recall my Create method and keep getting the selected value and updating the new list box.
Here I have the cshtml code
<select name="cboGender">
#foreach (var Gender in ViewBag.Genders)
{
<option value="#Gender.GenderId">#Gender.Name</option>
}
</select>
<select name="cboUser">
#foreach (var User in ViewBag.UsersByGender)
{
<option value="#User.UserId">#User.Username</option>
}
</select>
Any help on how I can do this would be great.
If I understand your problem correctly then, you can try one of the following methods to retrieve data.
e.g.
public ActionResult SomeAction(string cboGender)
or try using
string Gender= Request.QueryString["cboGender"];
or
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["cboGender"];
}
there is no other way to do this without js.
Oh, maybe you can create a button to sumbit the form,so your server side can get the value,
Request.Params["cboGender"] will effective. then filter user,render the page(it means refresh and bad experience ), is that your want?
I guess you used to do with asp.net WebForm.
In fact , WebForm framework also encapsulated with much js(JQuery) code.
the best way is : use ajax to post the genderId to server method like belowe
[HttpPost]
public JsonResult GetUserByGenderId(int? genderId)
{
var list = AllUsers.Where(a => a.genderId == genderId);// filter user
return Json(list);// return serialized json or
return Json(list.Select(a=>new { a.UserName,a.UserId }).Tolist());
}
and the ajax would receive this json to render the cboUser.
There are lots of ways to do this, but based on the way you've asked the question I think the easiest would be to do something along these lines:
1: Put a new combo-box into the page for each group of users, and hide them by default (note here I'm not a foreach like you are but that's just for brevity of the example):
<select id="cboGender" name="cboGender">
<option id="Male">Male</option>
<option id="Female">Female</option>
<option id="Unspecified">Unspecified</option>
</select>
<select id="cboMale" class="user-combo" name="user" hidden>
<option id="1">Oscar</option>
<option id="2">Leo</option>
</select>
<select id="cboFemale" class="user-combo" name="user" hidden>
<option id="3">Kristy</option>
<option id="4">Wendy</option>
</select>
<select id="cboUnspecified" class="user-combo" name="user" hidden>
<option id="5">Jamie</option>
<option id="6">Charlie</option>
</select>
2: Use jQuery to listen for changes to the "cboGender" combo box, then show the appropriate combo box in response:
var onGenderChanged = function() {
var gender = $genders.val();
// Hide all gender combo boxes...
$userCombos.hide();
// ... then show the one corresponding to the selection
$("#cbo" + gender).show();
};
Here's a JSBin which shows a working implementation.
The advantage of doing this is it saves you a "round-trip" to get the gender specific users each time the user changes.
Another alternative would be to load the users with an AJAX request when a gender is selected, but that's a bit more involved.
HTH

How Can DeActivate Razor Html Encoding ?

In Razor view I have a Javascript function. This function take 2 URLS String in arguments and call AJAX to do operation.
When I generated Url string in Razor, Razor change the URLS. Like changed & to & and damage my query strings which used in my URL address. Also Html.Raw() has not work in this case.
What can I do ?
EXAMPLE:
In my Razor editor:
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'#(Html.Raw(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))','#Html.Raw(address + "/cancel/?id="+baseObject.Id+"&type="+dataTypeInt )','ReloadPage',true);return false;">
Edit
</a>
In result :
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'/PdfInstanceEdit/index/?id=1&type=270','/PdfInstanceEdit/cancel/?id=1`&`type=270','ReloadPage',true);return false;">
Edit
</a>
The URL address like :
address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt
Change to :
/PdfInstanceEdit/index/?id=1&type=270
In other world character & => &
Its usually a bad idea to try and combine server code and client strings inside the quotes of a property (ie onclick="something#(something())" )
Its better to just return the entire lot in a server side function
Here's how I would rework your code:
<a href="#" style="color:#0564c1;"
onclick="#Html.Raw(
String.Format(
"PopUpStart('POST','','',200,100,'{0}','{1}','ReloadPage',true);return false;"
, Url.Action("index",address,new{id = baseObject.Id, type = dataTypeInt})
, Url.Action("cancel",address,new{id = baseObject.Id, type = dataTypeInt})
)
)"/>
Edit
</a>
Also note the difference between #(Html.Raw()) and #Html.Raw() - you should use the latter!
As direct assignment of events such as onClick is frowned on these days, a better way to accomplish then may be through js:
Add a hidden field for Id and dataTypeInt to your page:
#Html.HiddenFor(model=> model.Id)
#Html.Hidden("dataTypeInt ", dataTypeInt)
Add an id to your anchor:
Edit
Then your script:
<script>
$(document).ready(function () {
readyLinks();
});
readyLinks = function(){
var id = $('#Id).val();
var dataType = $('#dataTypeInt').val();
var indexUrl = '/PdfInstanceEdit/index?id=' + id + '&type=' + dataType;
var cancelUrl = '/PdfInstanceEdit/cancel?id=' + id + '&type=' + dataType;
$('#editLink).on('click', function(){
PopUpStart('POST','','',200,100,indexUrl, cancelUrl,'ReloadPage',true);
return false;
});
};
</script>
You should use Html.Raw() as suggested in the comments, see the documentation.
As described in this thread, if you have a particular problem with the output encoded format, you could use the HttpUtility.HtmlDecode() function, see documentation.
#Html.Raw(HttpUtility.HtmlDecode(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))
But since this could be a solution I cannot address you problem precisely...
A friendly reminder: if you're trying to put a Javascript string inside an HTML attribute, the value must be encoded twice. It must first be Javascript-encoded, then that result must be HTML-encoded. You could inadvertently open an XSS hole in your site if you don't perform both encodings in the correct order.
Say you have a string s that you want to display to the client. You'd write your Razor markup as:
Click me
Note the explicit call to JavaScriptStringEncode. Then Razor's # syntax will auto-HtmlEncode this value before writing it to the response.

Mutliple checkbox with same name attribute looping

I have a html form that submits to a C# ashx handler that i'm hoping will insert/update the database
I've written this in PHP and Coldfusion, but I cannot figure out how to do this in C#
HTML form
<form id="copyto">
<input type="hidden" name="operation" value="update" />
<label><input type="checkbox" name="children[]" checked="checked" value="001">
Andrew Regan</label>
<label><input type="checkbox" name="children[]" checked="checked" value="101">
Arthur Regan, III</label>
<input type="checkbox" name="children[]" checked="checked" value="968">
Tim Reagan
</form>
C# ASHX handler
foreach(string key in context.Request.Params["children"])
{
ListDictionary updateParams = new ListDictionary();
updateParams.Add("rowid", key);
string sSql = #"insert into temp select * from children where c.id = :rowid";
dbi.ExecuteNonQuerySql(sSql, updateParams);
}
Typically i would iterate over the $_POST['children'] in php , and execute the sql
How exactly does this translate?
EDIT
ok ive almost gotten this, however my iterator goes over ALL of the request collection variables, i want it to go over only a specific named variable, in this case "children"
i.e localhost/page?operation=update&children=9&children=8&children=17
foreach(string key in context.Request.QueryString)
{
ListDictionary updateParams = new ListDictionary();
updateParams.Add("row_id", context.Request.QueryString[key]);
string sSql = #"insert into dug select :row_id from dual";
dbi.ExecuteNonQuerySql(sSql, updateParams);
}
i want it to ignore everything but the specific var
If you are doing a post. I think something like this would work.
<input type="checkbox" name="children" value="108"/>
<input type="checkbox" name="children" value="109"/>
<input type="checkbox" name="children" value="110"/>
<input type="checkbox" name="children" value="111"/>
The browser will send all of the values comma seperated to the server when the form is submited
Then on your server side you can do this:
var selected = context.Request.Form["children"].Split(',');
Selected will be an array of strings for each value that was passed in by the browser. You can then loop over them and do whatever you need to.
Hope this helps some.
I was just working on this yesterday. I ended up using a hidden field that will hold the multiple checked checkbox id's. So, if that route works for you, you could create a checkboxlist editor template or control. This could have a script such as:
(tempId will hold the common "name" attribute's value for your checkbox/checkboxlist, and we have the "somehiddenfield" hidden field to hold the selected values)
<script>
$(function () {
var arrTmp = [];
//Update array on selection change
$('input[name="#String.Format("{0}[]", tempId)"]').change(function () {
arrTmp = [];
$('input:checked[name="#String.Format("{0}[]", tempId)"]').each(function () { arrTmp.push($(this).val()); });
$('input[id="somehiddenfield"]').val(arrTmp.join(','));
});
});
</script>
Then, on postback on the server-side the form collection will simply have the hidden field we wrote the checked values into. Split that in whatever way works for you (like comma separated in my example) and you're good to go. My server-side is implemented in MVC but for WebForms you can pull the elements from the Request.Form dictionary (Request.Form["somehiddenfield"].ToString()) or even Request.Params as you are using.
Right after i put out the bounty of course -_-
foreach (string k in context.Request.QueryString)
{
if (k.StartsWith("children")){
foreach (string v in context.Request.QueryString.GetValues(k)){
ListDictionary updateParamss = new ListDictionary();
updateParamss.Add("row_id", v);
string Sql = #"insert into dug select :row_id from dual";
dbi.ExecuteNonQuerySql(Sql, updateParamss);
}
}
}

How to use C# enumeration values in JavaScript

I have got an enumeration in C# ie something like Category.cs.
In a dropdownlist we are binding values.
So if the user selects some specific value in dropdown it will hide one div.
So i want to get the enumeration value in javascript ie want to compare the enumeration value with one selected value in javascript.
Mahesh
Suppose you have such enum with numeric values:
public enum Colors
{
Yellow = 1,
Red,
Blue,
Green,
Purple
}
First of all, in the code behind (Page_Load event) register JavaScript code that will build client side structure that hold the same data:
string strJS = string.Format("var arrColors = {{{0}}}; ",
string.Join(", ", Enum.GetNames(typeof(Colors)).ToList().ConvertAll(key =>
{
return string.Format("{0}: {1}", key, (int)((Colors)Enum.Parse(typeof(Colors), key)));
}).ToArray()));
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "enum", strJS, true);
Now arrColors is JS variable with both keys and values of your enum.
To use it, have such code for example:
<script type="text/javascript">
function SelectionChanged(oDDL) {
var selectedValue = oDDL.value;
var enumValue = arrColors[selectedValue] || "N/A";
alert("enum value for '" + selectedValue + "' is: " + enumValue);
}
</script>
And the drop down should look like this:
<select onchange="SelectionChanged(this);">
<option>Select..</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
</select>
System.Enum.GetNames(typeof(yourenumerationtype)) - returns an array of strings, which represents enumeration items' names

Categories