I have a radio button in a foreach loop within a form to be posted. I want the first one to be checked when they are listed. checked = "checked" below doesn't help. It only works if there is a single radio button.
<form action="/logged/hotel" method="post" >
#foreach (var item in ViewBag.companies)
{
<input type="radio" name="graph" value="#item.Value" checked="checked" /> #item.Text<br />
}
<input type="submit" value ="LOG IN" />
</form>
Add name attribute, this will group your radio buttons together and only displayed one as checked.
Only one radio button in a set can be checked.
all your radio buttons are in the same set.
you want to put them each in a different set so say
name="#item.Value"
However MVC wont like that, so you will have to do something like
[HttpPost]
public ActionResult MyGraphPage(GraphViewModel vm){
foreach(var company in MyDataContext.Companies){
if(Request.Form.AllKeys.Contains(company.Value){
//show the graph
}
}
If you just want the first one to be checked you can do this, its not the most elegant solution, but works.
<form action="/logged/hotel" method="post" >
#{
var isfirst = true;
}
#foreach (var item in ViewBag.companies)
{
if (isfirst) {
isfirst = false;
<input type="radio" name="graph" value="#item.Value" checked="checked" />#item.Text<br/>
} else {
<input type="radio" name="graph" value="#item.Value"/>#item.Text<br/>
}
}
<input type="submit" value ="LOG IN" />
</form>
#{
bool isFirstChecked = false;
foreach (var item in ViewBag.companies)
{
<input #(isFirstChecked ? "" : "checked") type="radio" name="graph" value="#item.Value" checked="checked" />
#item.Text
<br />
isFirstChecked = true;
}
}
Related
my model -
public class Model
{
public String SelectedValue;
}
action method -
public ActionResult Index()
{
Model model = new Model();
model.SelectedValue = "a";
return View("Index1", model);
}
view -
<input type="radio" name="Group1" value="a" data-bind="attr: { checked: SelectedValue }" />
<input type="radio" name="Group1" value="b" data-bind="attr: { checked: SelectedValue }" />
<input type="radio" name="Group1" value="c" data-bind="attr: { checked: SelectedValue }" />
<script type="text/javascript">
var data = #Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
BindData();
</script>
My javascript -
function BindData() {
viewModelData = ko.mapping.fromJS(data);
ko.applyBindings(viewModelData);
}
When my view is rendered, it renders all three radio buttons with the one with value = "c" selected. But from action method i am selecting radio button with value "a". why is it so?
Can anyone please help me understanding whether i have any issue with my code or how does knockout handle radio button selections internally. Thanks!
Use the checked binding instead of the attr binding which is directly created for this scenario:
The checked binding links a checkable form control — i.e., a checkbox (<input type='checkbox'>) or a radio button (<input type='radio'>) — with a property on your view model.
So in your case you need to write:
<input type="radio" name="Group1" value="a" data-bind="checked: SelectedValue" />
<input type="radio" name="Group1" value="b" data-bind="checked: SelectedValue" />
<input type="radio" name="Group1" value="c" data-bind="checked: SelectedValue" />
Demo JSFiddle.
I'm new to ASP.net MVC and I am struggling to make this work at the moment. I have a controller method called Add, it looks like this:
public ActionResult Add()
{
// check user is authenticated
if (Request.IsAuthenticated)
{
return View();
}
return RedirectToAction("Index", "Home");
}
//
// POST: /Home/Add
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(string title, string description, string priority, string color, FormCollection collection)
{
if (ModelState.IsValid)
{
// create instance of todo object
todo obj = new todo();
try
{
// gather fields
obj.priority = Convert.ToInt32(priority);
obj.color = Convert.ToInt32(color);
obj.title = title;
obj.description = description;
todosDataContext objLinq = new todosDataContext();
// get the users id, convert to string and store it
var userid = Membership.GetUser().ProviderUserKey;
obj.userid = userid.ToString();
// save
objLinq.todos.InsertOnSubmit(obj);
objLinq.SubmitChanges();
return RedirectToAction("Index", "Home");
}
catch
{
return View(obj);
}
}
return RedirectToAction("Index", "Home");
}
If data is sent via POST to the method, it should add the data to the database. That is working fine and everything is added correctly. However, the RedirectToAction is not firing, and the application gets stuck at /Home/Add, when it should redirect to /Home/Index. The view loads however, so it shows /Home/Index but the URL says /Home/Add.
Here is a copy of the partial view that contains the form:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<todo_moble_oauth.Models.todo>" %>
<% using (Html.BeginForm()) { %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<h3>Title:</h3>
<div class="editor-field">
<input type="text" name="title" />
</div>
<h3>Description:</h3>
<div class="editor-field">
<input type="text" name="description" />
</div>
<h3>Priority:</h3>
<div class="editor-field">
<select name="priority">
<option value="1">Low</option>
<option value="2">Medium</option>
<option value="3">High</option>
</select>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<h3>Color:</h3>
<input type="radio" name="color" id="radio-choice-1" value="0" checked="checked" />
<label for="radio-choice-1">None</label>
<input type="radio" name="color" id="radio-choice-2" value="1" />
<label for="radio-choice-2">Red</label>
<input type="radio" name="color" id="radio-choice-3" value="2" />
<label for="radio-choice-3">Blue</label>
<input type="radio" name="color" id="radio-choice-4" value="3" />
<label for="radio-choice-4">Yellow</label>
</fieldset>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
So data is being sent to the database and stored, however the redirect is broken.
Turns out it is an issue with jQuery mobile, this threads solution resolved the issue for me:
jQuery Mobile/MVC: Getting the browser URL to change with RedirectToAction
bool isChecked = false;
<input type="checkbox" name="x" checked="#isChecked" />
In MVC 4, The above code will be generate as
<input type="checkbox" name="x" />
But in MVC 3,Need to write like this:
bool isChecked = false;
#if(isChecked)
{
<input type="checkbox" name="x" checked="checked" />
}
else
{
<input type="checkbox" name="x" />
}
If we are Microsoft developers, Which assembly need to modify and how to modify it?
How to customize the upgrade code?
Plase help me,thanks!
To be honest I don't really understand the question after those code blocks, but I can say that you can use inline condition in your views in ASP.NET MVC3. Something like that for example:
bool isChecked = false;
<input type="checkbox" name="x" #(isChecked ? "checked=checked" : "") />
It's shorter and it will produce code like that:
<input type="checkbox" name="x">
And BTW, there is a helper method Html.CheckBox to create checkbox in your view and in second parameter you can indicate if you want it to be checked:
#{bool isChecked = false;}
#Html.CheckBox("x", isChecked)
And that will rendrer this:
<input id="x" type="checkbox" value="true" name="x">
<input type="hidden" value="false" name="x">
Try it on your own.
I have an aspx page with many buttons and i have a search button whose event i want to be triggered when user press enter.
How can i do this?
You set the forms default button:
<form id="Form1"
defaultbutton="SubmitButton"
runat="server">
Make it the default button of the form or panel.
Either one has a DefaultButton property that you can set to the wanted button.
$(document).ready(function() {
$("#yourtextbox").keypress(function(e) {
setEnterValue(e);
});
});
function setEnterValue( e) {
var key = checkBrowser(e);
if (key == 13) {
//call your post method
}
function checkBrowser(e) {
if (window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return key;}
call the above function and it will help you in detecting the enter key and
than call your post method.
The best way to make from make actions using enter button and on click of the button without the headache to write js check for each input you have if the user press enter or not is using submit input type.
But you would face the problem that onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
i have an check boxlist with (6 items under it). and i have an search button. if user clicks Search button it gets all the result.
i am binding the items for checkboxlist using database in .cs file
condition1:
but now if user selects a checkbox[item1] its gets selected
and he tries to select an 2 checkbox[item2] then firstselected checkbox[item1] should be unselected. only checkbox[item2] should be selected
condition 2:
now if user as selected checkbox1 [item1] it gets selected. and now if user again clicks on checkboxi[item1] then it should get deselected.
either you can provide me the solution in javascript or JQuery
any help would be great . looking forward for an solution
thank you
use Radio button. The only problem you will face is when you want to de-select the radio button. You can write in a javascript for 'onClick' of radio button. The onClick function can check whether radio button is selected, if it is not select it else deselect it.
Hope this helps. See Example
RDJ
While I definitely agree with the consensus that radio buttons are the way to go for your described use-case, here is a little snipped of jquery that will cause checkboxes to behave like radio buttons. You simply need to add a "groupname" attribute to your checkbox tag.
HTML:
<fieldset>
<legend>Group 1 - radio button behavior</legend>
<input type="checkbox" groupname="group1" value="1" /> Checkbox 1<br />
<input type="checkbox" groupname="group1" value="2" /> Checkbox 2<br />
<input type="checkbox" groupname="group1" value="3" /> Checkbox 3<br />
<input type="checkbox" groupname="group1" value="4" /> Checkbox 4<br />
<input type="checkbox" groupname="group1" value="5" /> Checkbox 5<br />
</fieldset>
<fieldset>
<legend>Group 2 - radio button behavior</legend>
<input type="checkbox" groupname="group2" value="1" /> Checkbox 1<br />
<input type="checkbox" groupname="group2" value="2" /> Checkbox 2<br />
<input type="checkbox" groupname="group2" value="3" /> Checkbox 3<br />
<input type="checkbox" groupname="group2" value="4" /> Checkbox 4<br />
<input type="checkbox" groupname="group2" value="5" /> Checkbox 5<br />
</fieldset>
<fieldset>
<legend>Group 3 normal checkbox behavior</legend>
<input type="checkbox" value="1" /> Checkbox 1<br />
<input type="checkbox" value="2" /> Checkbox 2<br />
<input type="checkbox" value="3" /> Checkbox 3<br />
<input type="checkbox" value="4" /> Checkbox 4<br />
<input type="checkbox" value="5" /> Checkbox 5<br />
</fieldset>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('input[type=checkbox]').click(function() {
var groupName = $(this).attr('groupname');
if (!groupName)
return;
var checked = $(this).is(':checked');
$("input[groupname='" + groupName + "']:checked").each(function() {
$(this).prop('checked', '');
});
if (checked)
$(this).prop('checked', 'checked');
});
});
</script>
I'm sure there are opportunities to increase brevity and performance, but this should get you started.
Why don't you use radio buttons, they are ideal for the purpose that you mentioned.
Edit:
If you necessarily want to use checkbox list then assign some logical ids to those checkboxes so that you can access them in JavaScript.
On each onclick event of the checkboxes call the JavaScript and in the JavaScript loop through and see
If any checkbox is checked other
than the present clicked checkbox,
then make them unselected.
If the present checkbox is already
checked then just toggle it.
You can see if a checkbox is checked using $("#checkboxId").is(":checked") which returns true if a checkbox is checked.
Thanks
this was the code that helped me to solve this issue
just add the script -
var objChkd;
function HandleOnCheck()
{
var chkLst = document.getElementById('CheckBoxList1');
if(objChkd && objChkd.checked)
objChkd.checked=false;objChkd = event.srcElement;
}
and register the client event to the 'CheckBoxList1' at the Page_load as
CheckBoxList1.Attributes.Add("onclick","return HandleOnCheck()");
You might want to have a look at the MutuallyExclusiveCheckBoxExtender.
.aspx
<asp:CheckBoxList id="chkList" runat="server" RepeatLayout="Flow" />
.js
$(document).ready(function () {
LimitCheckboxes('input[name*=chkList]', 3);
}
function LimitCheckboxes(control, max) {
$(control).live('click', function () {
//Count the Total Selection in CheckBoxList
var totCount = 1;
$(this).siblings().each(function () {
if ($(this).attr("checked")) { totCount++; }
});
//if number of selected item is greater than the max, dont select.
if (totCount > max) { return false; }
return true;
});
}
PS: Make sure you use the RepeatLayout="Flow" to get rid of the annoying table format.
we can do in java script to get the solution for this.
For this first get the id of the checked item and go thorough the remaining items using loop then unchecked the remaining items
http://csharpektroncmssql.blogspot.com/2011/11/uncheck-check-box-if-another-check-box.html
My jQuery solution for this is coded as follows:
$(document).ready(function () {
SetCheckboxListSingle('cblFaxTypes');
});
function SetCheckboxListSingle(cblId) {
$('#' + cblId).find('input[type="checkbox"]').each(function () {
$(this).bind('click', function () {
var clickedCbxId = $(this).attr('id');
$('#cblFaxTypes').find('input[type="checkbox"]').each(function () {
if (clickedCbxId == $(this).attr('id'))
return true;
// do not use JQuery to uncheck the here because it breaks'defaultChecked'property
// http://bugs.jquery.com/ticket/10357
document.getElementById($(this).attr('id')).checked = false;
});
});
});
}
Try this solution:
Code Behind (C#) :
foreach (ListItem listItem in checkBoxList.Items)
{
listItem.Attributes.Add("onclick", "makeSelection(this);");
}
Java Script :
function makeSelection(checkBox)
{
var checkBoxList = checkBox;
while (checkBoxList.parentElement.tagName.toLowerCase() != "table")
{
checkBoxList = checkBoxList.parentElement;
}
var aField = checkBoxList.getElementsByTagName("input");
var bChecked = checkBox.checked;
for (i = 0; i < aField.length; i++)
{
aField[i].checked = (aField[i].id == checkBox.id && bChecked);
}
}