How to get selected rows using checkbox in asp.net MVC - asp.net-mvc

Hi i've a problem related to html.checkbox in my MVC application.
My scenario is:
I've a list(index view) page where i bind data from the database with a checkbox to select/deselect the item. when i click save button i want to get selected rows to save those items back to db.
i used
1. <input type="checkbox" id="chk2" value="<%= item.recid %>" >
// I'm not getting value of chk2 in serverside
2. <%= html.CheckBox("chk1")%>
// i'm getting chk1 in serverside with value like 'true,false,true,false...'
in my model view iteration.
So how to do that in MVC application?

This is how I do it...
In the view, give all your checkboxes the same name and a unique value.
<input type="checkbox" name="MyCheckboxes" value="<%= item.recid %>" >
In your controller action method, pass an IList with the name of the checkboxes.
public ActionResult MyActionMethod(IList<string> MyCheckboxes)
{
...
}
You'll receive in MyCheckboxes a list of the values of only those checkboxes that were selected.

For 1), you need to specify a name on the input element.
You then need to match that name to a parameter on your Action Method.

Related

ViewModel binding without SelectList in ASP.NET MVC

In my ASP.NET Core application, I have an ASP.NET MVC View which displays a list of products. (I guess this applies to other versions of MVC as well).
When I select an item from this list and submit the page, I want the selected product ID to be bound to a ViewModel property in the action method of the controller. I am using POST for this.
I do NOT want to use SelectList for rendering the list of products due to some formatting issues. Therefore I am looping over the list in my view.
How can I bind the selected product with the ProductId property of the inbound ViewModel object?
It's unclear what you mean by "select an item from this list and submit the page". Are you picking an item, potentially filling out more fields, and then submitting the whole shebang, or does picking an item constitute submitting the form. Depending on the situation there's a few approaches:
If picking an item submits the form, then you can simply make the "Select" button a submit button and give it a name and value. For example:
Item 1 <button type="submit" name="ProductId" value="1">Select</button>
Whichever "Select" button is clicked, then, will have its value posted as ProductId.
If you need to pick an item while remaining on the page to fill out other fields, then you can use radio buttons as an alternative to a select list. This is similar to approach above, except you will not instantly post the form. Your inputs would look similar though:
<label>
<input type="radio" name="ProductId" value="1"> Item 1
</label>
<label>
<input type="radio" name="ProductId" value="2"> Item 2
</label>
...
Finally, if you need to not instantly submit and you do not want to use radio buttons either, then your only real option is using JavaScript to set a hidden input. You would bind to the click event of your "Select" button or whatever and then set a hidden input with name="ProductId" to the appropriate value. Then, when you finally submit the form, the value of the hidden input will be posted as ProductId.

TextBox value + TextBox value send one value

How can I concenate two texboxes in MVC, so when you click submit it will send values from two textboxes.
For example
<form method="get" action="#Url.Action("Index")">
#(Html.TextBox("q", Model.Search.FreeSearch))
??? //i need here another textbox
<input type="submit" value="Search"/> //when I click submit it will send values from both textboxess
</form>
Thanks for any idea...
If you add another field ( textbox) in the model and then pass this field from the model,
and create strongly typed view, then you can set two textboxes(fields) and send both value
and in the controller you can concate both field values.
e.g. model.firstname + model.lastname
hope this idea helps you.

Binding checkboxes to array with Knockout.js (MVC Razor)

I have a Knockout.js view model that looks like this:
"UserName":null,
"FirstName":null,
"LastName":null,
"Countries":{
"arrCountries":[]
}
And a set of country checkboxes that all must be rendered with the same data-bind value (I'm using this custom CheckBoxListFor helper, which can apply custom HTML to each checkbox, but it's the same custom HTML for each checkbox. It takes a property that lists every available country from my razor view model to create the checkboxes, and then renders some as marked based on another razor view model property).
The checkbox values are integers (1, 2, 3, etc) and it's those integers that I'd like to throw into the arrCountries property of the view model.
Here's how a checkbox is rendered as it stands at the moment:
<input checked="checked" data_bind="checked: ???" id="Countries.arrCountries107" name="Countries.arrCountries" type="checkbox" value="1"></input>
I've proven the concept of using viewModel.Countries.arrCountries.push(1); to update the view model (followed by an alert that gives me a count of the elements in arrCountries to prove that the push worked), but I can't seem to get the data-bind HTML property on the checkboxes to wire up so that they check and uncheck as I send push and remove commands.
Any help much appreciated!
Make the checked data attribute point to the selected countries. If the checkbox's value is in the array of checkboxes, then it will be checked. It won't otherwise.
<input checked="checked" data-bind="checked: Countries" type="checkbox" value="3"></input>
Take a look at this fiddle I put up.
http://jsfiddle.net/u8xP9/3/

How do you handle the output of a dynamically generated form in ASP.NET MVC?

Say you create a form using ASP.NET MVC that has a dynamic number of form elements.
For instance, you need a checkbox for each product, and the number of products changes day by day.
How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.
Just give each checkbox a unique name value:
<input class="approveCheck" id="<%= "approveCheck" + recordId %>"
name="<%= "approveCheck" + recordId %>" type="checkbox" />
Then parse the list of form values in the Action, after submit:
foreach (var key in Request.Form.Keys)
{
string keyString = key.ToString();
if (keyString.StartsWith("approveCheck", StringComparison.OrdinalIgnoreCase))
{
string recNum = keyString.Substring(12, keyString.Length - 12);
string approvedKey = Request.Form["approveCheck" + recNum];
bool approved = !String.IsNullOrEmpty(approvedKey);
// ...
You don't need to pass form values as arguments; you can just get them from Request.Form.
One other option: write a model binder to change the list into a custom type for form submission.
Per Craig's answer.. that is safer. There are quirks to posting multiple form elements with the same name. I would add that it would be wise to wrap the logic that makes the "collection" of controls in a way similar to WebForms. Web Forms prepend the container control's name and adds an index. For example, in a Repeater the form elements inside would be named (something like) RepeaterName_Element1, RepeaterName_Element2. When you go to get the elements out, you have to use FindControl or something of the sort.
Depending on the binders you are using, this should work:
<%var i = 0;
foreach (var product (IList<ProductSelection>)ViewData["products"]) {%>
<%=Html.Hidden(string.Format("products[{0}].Id", i), product.Id)%>
<%=Html.Checkbox(string.Format("products[{0}].Selected", i))%>
<%=product.Name%><br/>
<%}%>
...which will result in HTML something like this (notice the array notation on the names):
<input name="products[0].Id" type="hidden" value="123">
<input name="products[0].Selected" type="checkbox">
Widget
<input name="products[1].Id" type="hidden" value="987">
<input name="products[1].Selected" type="checkbox">
Gadget
...and the controller method that handles the post:
public ActionResult SelectProducts(IList<ProductSelection> products)
{
...
}
Upon binding, products parameter will contain two instances of ProductSelection.
One caveat is that I have not used the new default binding for complex objects. Rather I am using either the NameValueDeserializer or CastleBind, both from MvcContrib. They both behave this way. I am guessing binding in the Beta will work the same way.
Depending on your data, you could either output a 'CheckboxList' (which is not possible in the newer versions any more) and use a string[] parameter, or you could set up multiple forms and just modify the action.

DropDownList in conjunction with file upload in asp.net mvc

I have a file upload function in my asp.net mvc application that allows users to upload an xslx file containing data that should be persisted to a database. That data can be related to one of many categories. I need to be able to discern which category the data that is coming in is supposed to be related to, so I thought that a drop down list would be perfect for the job. However, I don't know how to get at the lists selected value when the user posts the data. This is what the code for the form looks like:
<form action="/Import/UploadFiles/" method="post" enctype="multipart/form-data">
<fieldset id="fileImport">
<legend>Importinställningar</legend>
<label for="file">Importfil:</label>
<input type="file" id="file" name="file" />
<%= Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewData["assignments"]) %>
<p>
<input type="submit" value="Spara"/>
<input type="button" value="Avbryt" onclick="window.location.href='/'" />
</p>
</fieldset>
</form>
Since I am dealing with a file upload scenario I don't have an action link that I can use to pass data to the controller, but rather an input with the type submit.
How should I go about reading the select value of the drop down list so that its selected value can be passed to the Controller?
There are a couple of different ways that you can make this work. First, add a string parameter named Name to your UploadFiles method. The default binder will fill it in from the form value with the same name. Alternatively, you can use the ValueProvider inside the controller -- if you use the same action for both rendering the view and responding to the post, for instance -- to extract the value of the parameter named Name.
public ActionResult UploadFiles( string Name )
{
...
}
or
public ActionResult UploadFiles()
{
string name = this.ValueProvider.ContainsKey("Name")
? this.ValueProvider[key].AttemptedValue
: null;
...
}

Resources