I have a partialview [_SearchProduct] within the main view, let’s say [product] view. The Partialview has a number of checkboxes segregated into different sections like search by company,search by product etc. with one [search] button.
A User can select multiple checkboxes. When user clicks [search] button I need to pass ids of all selected checkbox to controller action and re-render the page again considering the user’s selection . Please guide me how to pass selected checkbox ids to my controller action.
My partial view is something like below:
<fieldset>
<legend>By Company</legend>
<table style="border-style: none;">
<tr>
@{
int i = 0;
foreach (var item in Model.CompanyName)
{
i = i + 1;
<td style="border-style: none;text-decoration:none;" >
@Html.CheckBox("chkCompany",new {id="chkCompany_" + Model.CompanyId.Tostring()}) @Model.CompanyName
</td>
if (i == 5)
{
@:</tr><tr>
i = 0;
}
}
}
</tr>
</table>
</fieldset>
<fieldset>
<legend>By Product</legend>
<table style="border-style: none;">
<tr>
@{
i = 0;
foreach (var item in Model.Product)
{
i = i + 1;
<td style="border-style: none;text-decoration:none;" >
@Html.CheckBox("chkProduct",new {id="chkProduct_" + Model.CompanyId.Tostring()}) @Model.ProductName
</td>
if (i == 10)
{
@:</tr><tr>
i = 0;
}
}
}
</tr>
</table>
</fieldset>
- checkboxes are dynamic
- Checkbox id represent the primarykey of respective table based on which i do filtering.
Please guide me>>
So it sounds like you have a structure containing names (of companies/products), and ids.
I would create a View Model structure that looked like
Then in order to bind them you could do
Then provided your post takes a parameter of
PartialViewModel(or someMainViewModelwhere that contains an instance ofPartialViewModel), you’ll have lists of companies and products binded. You can loop through the list, and take the respective ids of anything checked to be included.Edit: If you wanted a single comma separated array to be posted, it would be possible by by creating an onclick event for your checkboxes, and then setting a value of a hidden input every time a checkbox is clicked. But then your code would only work with JavaScript enabled. If you need a comma separated string, you can create it server side with the view model I suggested.