i have a form in which there can be multiple radio buttons generated dynamically in the view ,on the form submitted how can i collect the values in the controller. For example there are radio buttons dynamically generated like Gender (Male and Female), Education (BS,MS,BCS) . how can i have there value in the container.
If you know the names of the radio buttons you could use action parameters. If the names are arbitrary you could fetch the values from a FormCollection parameter passed to your POST action (it is a NameValueCollection so you could loop through the key and get the corresponding values).
Personally I would recommend you using deterministic names:
Gender:
<input type="radio" value="M" name="radios[0]" />
<input type="radio" value="F" name="radios[0]" />
Education:
<input type="radio" value="BS" name="radios[1]" />
<input type="radio" value="MS" name="radios[1]" />
<input type="radio" value="BCS" name="radios[1]" />
And in your controller action you could use a collection:
[HttpPost]
public ActionResult Update(string[] radios)
{
// The radios collection will contain the selected values like:
// radios[0] = "F"
// radios[1] = "MS"
...
}
The only way would be to use form collections if they are dynamically generated radio buttons.
public ActionResult controllername(FormCollection form)
{
foreach(string radioName in dynamicRadioList)
{
var value = form[radioName];
//blah blah
}
}
Related
I have a set of radio buttons on a razor page, and I want to get and use the selected value of these radio buttons in my server-side code once the form has been submitted. HTML for radio buttons:
<label><input class="boost_radio" onclick="boostNo(1)" asp-for="Boost_No.Number" type="radio" name="boostno" value=1 checked="checked" disabled="disabled" />1</label>
<label><input class="boost_radio" onclick="boostNo(2)" asp-for="Boost_No.Number" type="radio" name="boostno" value=2 disabled="disabled" />2</label>
<label><input class="boost_radio" onclick="boostNo(3)" asp-for="Boost_No.Number" type="radio" name="boostno" value=3 disabled="disabled" />3</label>
<label><input class="boost_radio" onclick="boostNo(4)" asp-for="Boost_No.Number" type="radio" name="boostno" value=4 disabled="disabled" />4</label>
<span asp-validation-for="Boost_No.Number"></span>
I am using model binding to get the value on the server-side:
public class BoostNo
{
[Required(ErrorMessage = "Select Number of Boost Units!")]
public int Number { get; set; }
}
This class is instantiated as follows:
[BindProperty]
public BoostNo Boost_No { get; set; }
Unfortunately, every time I run the code, I get a Boost_No.Number = 0. I tried changing the data type to a string, but I just get string = null.
I am trying to use the model-bound variable in the handler method assigned to the form the radio buttons are contained in.
I'd really appreciate it if someone could help me out. Thanks.
Edit:
Here is the handler method in which the model binding is used:
public IActionResult OnPostSubmit()
{
//save data to sql db
SaveData();
//then some other unrelated stuff
}
And the SaveData() method:
public void SaveData()
{
//stuff
//now how the radio button values are actually used
for (int param_i = 1; param_i <= Boost_No.Number; param_i++)
{
//...
}
//then a paramaterized sql database query
}
All of your radio inputs are set to disabled so no value will be passed in the form collection when the form is submitted. Remove the disabled (and the name) attributes from the inputs:
<label><input class="boost_radio" onclick="boostNo(1)" asp-for="Boost_No.Number" type="radio" value=1 checked="checked" />1</label>
<label><input class="boost_radio" onclick="boostNo(2)" asp-for="Boost_No.Number" type="radio" value=2 />2</label>
<label><input class="boost_radio" onclick="boostNo(3)" asp-for="Boost_No.Number" type="radio" value=3 />3</label>
<label><input class="boost_radio" onclick="boostNo(4)" asp-for="Boost_No.Number" type="radio" value=4 />4</label>
Here is a minimal Example I setup to make it work.
Here is my razor page handle and I use the same class implementation as you.
[BindProperty]
public BoostNo Boost_No { get; set; }
public IActionResult OnPost()
{
return Page();
}
Now in the HTML
<label><input asp-for="Boost_No.Number" type="radio value=1 checked="checked"/>1</label>
<label><input asp-for="Boost_No.Number" type="radio" value=2/>2</label>
<label><input asp-for="Boost_No.Number" type="radio" value=3/>3</label>
<label><input asp-for="Boost_No.Number" type="radio" value=4/>4</label>
Changes:
First remove the name attribute. Why? because the asp-for tag helper will create a name attribute for you. In addition to providing a name attribute you give it a value of boostno, the name attribute is used to bind the value to the Model, in other words your OnPost handle doesn't have a boostno parameter anywhere to get bound to.
Secondly if an input field is disabled the input value will be ignored. I would double check that before you submit the form open developer tools (F12) and double check your input field elements to make sure they are not disabled, even though the UI might suggest otherwise.
if these are individual radio buttons, you should have individual binding for each of those, for now you are using same for each of the radio button. (Boost_No.Number).
Either create a list of List and then bind individual radio button lik
"Boost_No[0].Number" or create different properties for each of those (your choice)
I have a list of items and I would like to delete items that are checked in a list of checkboxes.
I can't use something like CheckboxList since I'm using Grid.Mvc to display my lines. That is why I create checkboxes in each line with column.add("<input type="checkbox".....>);.
Every checkbox has its own ID:
<input type="checkbox" id="3">
<input type="checkbox" id="4">...
I would like to know how to pass all checked checkbox IDs to the controller (from there I will perform delete operations). How can I post an array of checked IDs from my form to my controller action with one button press?
Example of generated HTML:
<label><input type="checkbox" name="deletedItems" value="3"> Some label for 3</label>
<label><input type="checkbox" name="deletedItems" value="4"> Some label for 4</label>
...
<button type="submit">Submit</submit>
Controller action:
[HttpPost]
public ActionResult MyAction(int[] deletedItems)
{
// deletedItems contains all values that were checked
// when the submit button was clicked. Here you can
// loop through the array of IDs and delete by ID.
...
}
Note that the checkboxes do not have an id attribute. It is not used for model binding. Instead it has a name attribute named "deletedItems" that matches the name of the argument of the MyAction controller action, and that is what is used when model binding. The value attribute of checked checkboxes will be used to populate the deletedItems array of int[].
If you want generated html like
<label><input type="checkbox" name="deletedItems" value="3"> Some label for 3</label>
<label><input type="checkbox" name="deletedItems" value="4"> Some label for 4</label>
Then you can use the following code
<td>#Html.CheckBox("selectedItems", new { #value = #item.checkId })</td>
<td><input id="selectedItems" name="selectedItems" type="checkbox" value="11503" />
<input name="selectedItems" type="hidden" value="false" />
</td>
It won't pass selectedItems to controller.
I have a Ajax.BeginForm in my razor view. I want to have 3 check boxes.
Begineer
Intemidiate
advance
checkoxes can select for any combination. When I clicked submit button bellow method in my controller will triggered.
public PartialViewResult SearchCourseCriteria(){
var courses = from s in db.CourseCategories
select s;
return PartialView("_Courses", courses);
}
This is my view
#using (Ajax.BeginForm("SearchCourseCriteria", new AjaxOptions
{
UpdateTargetId = "CourseList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
}))
{
td>
#Html.CheckBoxFor()
</td>
<td>
<input type="submit" value="Search" class="btn " />
</td>
}
In my model there is field called CourseLevel. I want to know How to filter courses according to the selected checkboxes.
EX : If I select begineer and Intermidiate checkboex. I want to get all courseCategories from that levels. I dont know how to get that result. Help please.
In you view, generate 3 checkboxes for each value
<label>
<input type="checkbox" name="courselevel" value="Begineer" /> // Beginner?
<span>Begineer</span>
<label>
<label>
<input type="checkbox" name="courselevel" value="Intemidiate" /> // Intermediate?
<span>Intemidiate</span>
<label>
... // ditto for advance
Then add a parameter to the method
public PartialViewResult SearchCourseCriteria(string[] CourseLevel)
The value of CourseLevel will be an array of the selected checkboxes, for example [ "Begineer", "advance" ] if you checked the first and third checkboxes
You can then modify you query to
var courses = from s in db.CourseCategories
where CourseLevel.Contains(s.CourseLevel)
select s;
or
var courses= db.CourseCategories.Where(c => CourseLevel.Contains(c.CourseLevel));
Side note: I would recommend you use an enum to define the values for CourseLevel
Can someone please tell me why the id of the checkbox 'userId' returns null on POST
<input type='checkbox' onclick='$("#userId").val("#user.Id"); return true; '/>
#using (Html.BeginFormAntiForgeryPost(Url.Action("Index", "ChangeUserAccount"), FormMethod.Post))
{
<input type="text" id="userId" />
<input type="submit" id="btn" name="btnSubmit" value="Update" style="float:right;" />
}
[HttpPost, ActionName("Index")]
[Authorize]
public ActionResult IndexPOST(UserLoginRecordIndexVM model, int? userId)
{
So on screen the text box contains the correct ID of the checkbox, but when I click the 'Update' button NULL gets returned??
Why don't you leverage this helper:
#Html.TextBox("userId", null, new { id = "userId" });
This will add the appropriate id and name attributes to your textbox.
Just add the name attribute:
<input type="text" id="userId" name="userId" />
But, also make sure your action accepts it as a parameter, string userId, or that it's part of the model that's posted back. So, in your case you might just do this:
public ActionResult IndexPOST(UserLoginRecordIndexVM model, string userId)
I have a form in my asp.net mvc view as follow:
<%using (Html.BeginForm("SearchBorrowed", "Admin", FormMethod.Get))
{ %>
<%: Html.TextBox("searchTerm", Request.QueryString["searchterm"])%>
<input type="submit" value="Search" />
<br />
Is Returned :
<%:Html.CheckBox("IsReturned")%>
<%} %>
and here is the 'SearchBorrowed' action:
public ActionResult SearchBorrowed(bool IsReturned=false, string searchTerm = null)
{
IEnumerable<BorrwoinfInfo> bs;
//...Get from repository
return View(bs.ToList());
}
and finally routing settings :
routes.MapRoute(
"SearchBorrowed", // Route name
"{controller}/{action}/{*searchTerm}", // URL with parameters
new
{
controller = "Admin",
action = "SearchBorrowed",
searchTerm = UrlParameter.Optional
} // Parameter defaults
when I submit the form without checking 'IsReturned' Checkbox,
it returns result and the url gets as follow :
.../SearchBorrowed?searchterm=&IsReturned=false
But when I check IsReturned' Checkbox, the urls gets like this:
.../SearchBorrowed?searchterm=s&IsReturned=true&IsReturned=false
Why there is two IsReturned in above url ?!
How Could I fix this ?
Why there is two IsReturned in above url ?!
Because the Html.CheckBox helper generates an additional hidden input field with the same name as the checkbox. If you look at the generated HTML you will see that the helper generated the following 2 input fields:
<input type="checkbox" name="IsReturned" id="IsReturned" value="true" checked="checked" />
<input type="hidden" name="IsReturned" id="IsReturned" value="false" />
This is by design. This helper is intended to be bound to a boolean property on your view model. When a checkbox field is not checked no value is sent to the server, so if there was not no hidden field you wouldn't be able to bind it to a boolean field.
If you don't want this hidden field you could either write a custom helper or generate the checkbox field manually.