Radiobuttonlist selecteditem is always null - selecteditem

Quiz project, a question has a radiobuttonlist with either 2 items(T/F) or 4 items (a,b,c,d)
number of questions varies. Panel is used to show only one question at a time (show/hide).
after answering all questions user clicks on submit button and all answers should be saved in database. In code behind selecteditem is always null and value is always empty string.
<asp:DataList ID="dtQuestion" runat="server" RepeatDirection="Vertical" OnItemDataBound="FormatDataListRow" >
<ItemTemplate>
<asp:Panel id="panel" runat="server" BorderColor="#536895" BorderStyle="Solid" BorderWidth="1" style="display: none;" EnableViewState="true">
<asp:Label id="lblQuestionDesc" runat="server" Text="" ></asp:Label>
<asp:RadioButtonList id="rbl" runat="server" EnableViewState="true" > </asp:RadioButtonList>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
on submit click. I call a function that search the page for RBL I am able to see their correct ID's and list items but nothing is selected.
string id;
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButtonList"))
{
if (c.ID != "rbl")
{
id = c.ID;
al.Add(id + "," + ((RadioButtonList)c).SelectedItem.Value); //SelectedValue); //
}
}

It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RBL
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}

Try accessing the submitted value like this:
this.Request.Form[((RadioButtonList)c).UniqueID]
During debugging you can always check what values you've got in this.Request.Form collection.

Related

Adding another input field when a add button is pressed

Im trying to create an app that will have fields a user can enter information into. The problem is I don't know how many fields that will be. For example, lets say you have a recipe app where you enter the ingredients in. Some recipes may have 2 ingredients and some may have more. What I am wanting is the option if there are more fields needed than what is on the screen presently, the user can press a add button and it will create the additional fields as needed instead of having some potentially unused fields. I've been looking around trying to find an example of what I'm looking for and not having any luck. Any help would be much appreciated.
best approach will be a UITableView. There you can add as much cell as you need.
There is a apples example though it not as like as you want but you can get the picture.
Hope this helps.. :)
Try this it will help you..
<pre><div id="divingredient" class="input_wrapar_search">
<span>Ivingredient Type : </span>
<input type="text" maxlength="50" id="txtIngredient0" />
</div> </pre>
<script>
var counter = 0;
$("[id$=btnaddnew]").live("click", function (e) {
counter++;
if (counter > 10) {
alert("Can not add more than 10 price !");
return false;
}
$("#divingredient").append('<input type="text" maxlength="50" id="txtIngredient' + counter + '" />');
e.preventDefault();
});
$("[id$=btnremove]").live("click", function (e) {
if (counter == 0) {
alert("one price is manadatory !");
return false;
}
$("#txtIngredient" + counter).remove();
counter--;
e.preventDefault();
});
</script>
<asp:Button ID="btnaddnew" runat="server" Class="btn" Text="Add New" />
<asp:Button ID="btnremove" runat="server" Class="btn" Text="Remove" /></pre>

jQuery UI MultiSelect Widget: after postback only last selected element is checked

I am implementing this JQuery UI multiselect from
http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
I have managed to get it to use in my asp.net page, but for some reason after postback, the selected text shows only the last element checked.
Here is my Code
$("document").ready(function () {
$("#ListBox1").multiselect({
noneSelectedText: 'Select',
selectedList: 200
});
$("#ListBox2").multiselect({
noneSelectedText: 'Select',
selectedList: 200
});
function GetSelectedListBox() {
var array_of_checked_values = $("#ListBox1").multiselect("getChecked").map(function () {
return this.value;
}).get();
var array_of_checked_values1 = $("#ListBox2").multiselect("getChecked").map(function () {
return this.value;
}).get();
$("#HiddenField1").val(array_of_checked_values);
$("#HiddenField2").val(array_of_checked_values1);
}
});
<body>
<form id="form1" runat="server">
<div style="font:12px Helvetica, arial, sans-serif;">
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server"></asp:ListBox>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
</div>
<div>
<asp:Button ID="btn1" runat="server" Text="Press" OnClientClick="GetSelectedListBox();" onclick="btn1_Click" />
</div>
</form>
</body>
in my server side code
ListBox2.DataSource = dt;
ListBox2.DataTextField = "Id";
ListBox2.DataValueField = "ListValue";
ListBox2.DataBind();
protected void btn1_Click(object sender, EventArgs e)
{
Response.Write(HiddenField1.Value);
Response.Write(HiddenField2.Value);
}
Any ideas why is it showing only last selected element but the interesting this the values in the HiddenField is displaying "Value1,Value2,Value3, value21" whereas the widget box is only showing value21, and only value21 is disaplyed as checked in the widget when all the elements where checked prior to postback
Thanks
I have make a temporal fix, I already know is not the best solution, but it work until I find the right way to do it.
I have create a hidden field for each select and before submit the form I set the hidden fields with the value of options.
So I can get this values on the controller.
$('#muestraForm').submit(function() {
$("#hidden_temporal_field").val($("#select_field").val());
return true;
});
I was actually just having that same problem.
Try using a listbox with the selection mode as Multiple, I have a postback in my page and the values stay there
<asp:ListBox ID="ListBox1" SelectionMode="Multiple" runat="server"></asp:ListBox>
also, there doesn't seem to be a SelectedItem*s* for a listbox in asp.net only on forms so you need to do this manually something like this
private String GetSelectedItems(ListBox listbox)
{
String SelectedValues = "";
foreach ( ListItem item in listbox.Items)
{
if(item.Selected == true)
SelectedValues = SelectedValues + "," + item.Text ;
}
if (SelectedValues.Length > 1)
SelectedValues = SelectedValues.Remove(0, 1);
return SelectedValues;
}
This works for me values stay after each post back and I can access the list of selected values in code behing :) , let me know if it helps you

Jquery-Mobile: How to add the data dynamically to the select menu based on the text box value

I am new to jquery mobile. In my UI, one text box and one select menu are there. Initially select menu is empty.If the textbox value is more than 1 then some data is added to the select menu otherwise select menu is empty. For this, i am calling the function at the onchange of select menu but it is not working. Please can anybody help me.
Edit:
Ex:
$('#Goal_Time').bind( "focus", function(event, ui)
{
if(Goal_WeightVar.val() > 0)
{
Goal_WtVar = Math.abs(weightVar.val() - Goal_WeightVar.val());
Min_DurationVar = Math.round(Goal_WtVar * 2.2);
for(var i=0;i<10;i++)
{
$('#Goal_Time').append('<option value=Min_DurationVar>Min_DurationVar</option>');
}
}
});
thanks
Well Kinda working example:
http://jsfiddle.net/v5DC3/5/
JS
$('#Goal_WeightVar').live('change', function() {
var weightVar = 0; // for testing only
var goalWeightVar = $('#Goal_WeightVar').val();
if(goalWeightVar > 0)
{
Goal_WtVar = Math.abs(weightVar - goalWeightVar);
Min_DurationVar = Math.round(Goal_WtVar * 2.2);
for(var i=0;i<10;i++)
{
$('#Goal_Time').append('<option value='+Min_DurationVar+'>'+Min_DurationVar+'</option>');
}
$('#Goal_Time').listview('refresh');
}
});
HTML
<div data-role="page" id="Goal_Time_Page">
<div data-role="content">
<label for="Goal_WeightVar">Goal Weight:</label>
<input type="text" name="Goal_WeightVar" id="Goal_WeightVar" value="" />
<label for="Goal_Time" class="select">Goal Time:</label>
<select name="Goal_Time" id="Goal_Time">
<!-- Add options here -->
</select>
</div>
</div>
You will need to tweak it
As it says in the docs of jQuery Mobile, you have to tell the select menu to update it's contents by calling $('select').selectmenu();
If it still doesn't work you'll have to post a little sample code so I can have a look at it.
Edit:
Actually, that's not even necessary. If you have an empty <select id="to-append"></select>, you can just add options via $('#to-append').append('<option value="a">A</option>')!
The onchange event of the select is probably not the right event to do this though. The select will not change as long as it's empty, thus your event will never get triggered. Try the blur event of the text box.
jQuery Mobile Docs - Select

How to submit form with multi buttons with same value asp.netMvc

I need to build voting web site so, I have couple candidates and below them a vote button,
how I can find which of the buttons was submitted
thanks
Give each of your buttons a name, like so (notice they are both "submit" buttons)::
<input type="submit" name="buttonYes" value="Yes" />
<input type="submit" name="buttonNo" value="No" />
Then, in your controller, capture a parameter for each of the two button names like this:
public ActionResult Index(string buttonYes, string buttonNo) { ... }
You can then tell which button was pressed by checking to see which of these two parameters is not null; the one which is pressed with a have a value equal to the "value" attribute of the button, the other one will be null:
if (buttonYes != null)
{
// Then the yes button was preseed
}
else if (buttonNo != null)
{
// Then the no button was pressed
}
else
{
// Neither button was used to submit the form
// and we got here some other way
}
The reason this works is because the web browser sends the information for the submit button that was pressed as part of the HTTP post to the web server. The button that was not pressed will not be sent with the post, and therefore the parameter will be null.
There are lots of ways to rewrite and optimzie this, but this is the essence of it and shows the fundamentals that are at work--you can play with it from there.
I wouldn't use the button value, I would set it up so that the url used to do the post encodes the vote itself. You could do this a couple of ways.
Use links
<div class="left">
<img src="/images/candidate/#Model.Candidates[0].ID" alt="#Model.Candidates[0].Name" />
#Html.ActionLink( "Vote for " + Model.Candidates[0].Name, "count", "vote" )
</div>
<div class="right">
<img src="/images/candidate/#Model.Candidates[1].ID" alt="#Model.Candidates[1].Name" />
#Html.ActionLink( "Vote for " + Model.Candidates[1].Name, "count", "vote" )
</div>
Use separate forms
<div class="left">
#using (Html.BeginForm( "count", "vote", new { id = Model.Candidates[0].ID } ))
{
<img src="/images/candidate/#Model.Candidates[0].ID" alt="#Model.Candidates[0].Name" />
<input type="submit" value="Vote" />
}
</div>
<div class="right">
#using (Html.BeginForm( "count", "vote", new { id = Model.Candidates[1].ID } ))
{
<img src="/images/candidate/#Model.Candidates[1].ID" alt="#Model.Candidates[1].Name" />
<input type="submit" value="Vote" />
}
</div>
Either of the above can be adapted to work with AJAX as well. Note, if you care, you'll need to build in some mechanism to detect vote fraud, e.g., add a one-time nonce to the url to verify that it isn't used more than once; track the number of times a user has voted if they are authenticated, etc.

Update Drop Down Value in Grails using <g:submitToRemote>

I have just entered into the Grails arena.
I have a requirement where I want to put one drop down and one button on one page, and by clicking on button only that drop down values should be changed, other controls on the page should remain unchanged.
My code is as follows :
_connType.gsp
<div id="mappedDeviceDiv">
<select id="mappedDevice" name="mappedDevice" value="" style="width:200px">
<g:each in="${deviceList}" status="i" var="dl">
<option value="${dl}">${dl}</option>
</g:each>
</select>
<g:submitToRemote class="blackButton" update="mappedDeviceDiv"
url="${[controller:'resource',action:'getDeviceList']}"
value="Get Devices"/>
</div>
ResourceController.groovy
def getDeviceList = {
println "Getting NV devices.. + Nirmal" + params
def model = buildAccessRequestModel()
List<NVDeviceBean> deviceList = NVUtil.getDevices(params.datasource, null);
Collections.sort(deviceList);
List<String> devices = []
for(NVDeviceBean deviceBean : deviceList) {
devices.add(deviceBean.getName())
}
println "list = "+devices
model.putAt('deviceList', devices)
render (template:'config/connType',model:model)
}
So, in above scenario, it's setting the values in the devices perfectly, but at the view side in a drop down m getting whole connType page, instead of only list values which is in devices variable of controller.
Any help would be highly appreciated..
You might want to create/modify one of the controller actions to return a list of HTML options. You could even have this action render a template, too.
def getDeviceOptions = {
def options = []
// code that creates the option list goes here.
render(template:'config/optionList', model: [optionList: options ])
}
And the template...
<!-- config/_optionList.gsp -->
<g:each in="${optionList}" status="i" var="dl">
<option value="${dl}">${dl}</option>
</g:each>
Then, tell the g:submitToRemote tag to update the select object.
<g:submitToRemote class="blackButton" update="mappedDevice"
url="${[controller:'resource',action:'getDeviceOptions']}"
value="Get Devices"/>
That should get you started in the right direction.

Resources