.NET foreach checkboxes form into controller [duplicate] - c#

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.

Related

How to properly use Model Binding to get Radio Button value in Razor Pages

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)

Filter records in database according to the selected checkboxes using MVC

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

binding <input type="radio"> with Model field?

In a view I have two <input type="radio">, combine they make a radio group.
I want to bind them with a field of Model, in a way if value is true it should bind first radio button if false it should bind the other.
Please guide how it can be achived. I tried below code but it always checked the second radio no matter what value model has.
<div class="radiobuttons">
<input type="radio" name="LenderType" checked="#Model.Filter_Value" id="rbtnAllLenders" class="cb">
<input type="radio" id="rbtnMajorLendersOnly" checked="!#Model.Filter_Value" name="LenderType" class="cb">
</div>
The input typed as radio needs to have a value set. If the radio is checked, then the value is what is sent for the name in the model.
view model
public class SomeViewModel
{
public int MyRadioValue { get; set; }
}
input element
<input type="radio" value=1 name="MyRadioValue" />
<input type="radio" value=2 name="MyRadioValue" />
<input type="radio" value=3 name="MyRadioValue" />
Create Html Helper ....
public static HtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectListItems, RadioButtonListLayout layout)
{
var sb = new StringBuilder();
foreach (var item in selectListItems)
{
var itemId = string.Format(
CultureInfo.InvariantCulture,
"{0}_{1}",
helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)),
item.Value);
var itemHtml = string.Format(
CultureInfo.InvariantCulture,
"{0} <label for=\"{1}\">{2}</label>",
helper.RadioButtonFor(expression, item.Value, new { id = itemId }),
itemId,
item.Text);
if (layout == RadioButtonListLayout.Horizontal)
{
sb.Append("<span class=\"radiobuttonlist-horizontal\">");
sb.Append(itemHtml);
sb.AppendLine("</span>");
}
else
{
sb.Append("<div class=\"radiobuttonlist-vertical\">");
sb.Append(itemHtml);
sb.AppendLine("</div>");
}
}
return new HtmlString(sb.ToString());
}
Use it ...
#Html.RadioButtonListFor(x=>x.Id,Model.ListItem,RadioButtonListLayout.Horizontal)
You manual code is adding the selected attribute to both radio buttons. All the following are equivalent:
<input type="radio" ... checked />
<input type="radio" ... checked="selected" />
<input type="radio" ... checked="true" />
<input type="radio" ... checked="false" />
Note the last 2 are invalid values for the checked attribute, but still check the radio button. Since you have a group name, and only one button can be visually checked, the last one rendered is selected. Refer W3C specifications.
Use html helpers to bind to your model. If the model contains property string LenderType then
#Html.RadioButtonFor(m => m.LenderType, "All lenders", new { id = "All"})<label for="All">All lenders</label>
#Html.RadioButtonFor(m => m.LenderType, "Major lenders", new { id = "Major"})<label for="Major">Major lenders</label>
If the value of LenderType is "All lenders" the first option will be selected. If the value is "Major lenders", then the second option will be selected

Get posted value In C# ASP.NET

I have a dynamic form that allow to add many fields dynamically,
I Know how to get the value of single field in aspnet using : Request.Form["myField"],but here i have more than field and i dont know the count of these fields since these are dynamic
the fields name is "orders[]"
ex:
<form>
<input type="text" name="orders[]" value="order1" />
<input type="text" name="orders[]" value="order2" />
<input type="text" name="orders[]" value="order3" />
</form>
In php,
i get the values as an array by accessing $_POST['orders'];
ex:
$orders = $_POST['orders'];
foreach($orders as $order){
//execute ...
}
how can I do this in c# ?
Use Request.Form.GetValues.
Request.Form is a NameValueCollection, an object that can store a collection of items under the same key and the ToString displays the values in CSV format.
Markup:
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<asp:Button Text="text" runat="server" OnClick="ClickEv" />
Code behind:
protected void ClickEv(object sender, EventArgs e)
{
var postedValues = Request.Form.GetValues("postField[]");
foreach (var value in postedValues)
{
}
}
You would use Request.Form[]. Or if your form and fields had runat="server" and ids, you could just use the id in the codebehind and the .Text() method to access its value.
You can access everything that gets sent back to the server by using the Request object.
Request.Form.Items
Is a collection that will contain the item you are looking for.

ASP.NET MVC C# dynamic radiobuttons getting formcollection

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
}
}

Categories