I have the view that contains the checkbox and Submit button as shown below.
@using (Html.BeginForm())
{
<fieldset>
<legend style="font-size: 100%; font-weight: normal">Delete</legend>
<p> Are you sure you want to delete?</p>
@foreach (string resource in resources)
{
if (resource != "")
{
<input type="checkbox" name="Resources" title="@resource" value="@resource" checked="checked"/>@resource
<br />
}
}
<br />
@Html.HiddenFor(m => m.AttendeeListString)
@Html.HiddenFor(m => m.ResourceListString)
<span class="desc-text">
<input type="submit" value="Yes" id="btnYes" />
</span>
<span class="desc-text">
<input type="submit" value="No" id="btnNo" />
</span>
</fieldset>
}
Below is the Controller code…
public ActionResult DeleteResource(RoomModel roomModel)
{
...
}
RoomModel contains some other data…
Now how can i access the checkbox value in controller?
Note : I have lot more information that need to be send to Controller when i clicked on submit button… Can anybody suggest some solution….
Answer :
I have added these two property to My model
public List<SelectListItem> Resources
{
get;
set;
}
public string[] **SelectedResource**
{
get;
set;
}
And My view check box i have updated as follows
@foreach (var item in Model.Resources)
{
<input type="checkbox" name="**SelectedResource**" title="@item.Text" value="@item.Value" checked="checked"/>@item.Text
<br /><br />
}
And in Controller …
if (roomModel.SelectedResource != null)
{
foreach (string room in roomModel.**SelectedResource**)
{
resourceList.Add(room);
}
}
Note: The name of check box and Property in the model should be same. In my case it is SelectedResource
You have a few options. The easiest would be:
1) Parameter bind a view model with the Resources property. I recommend this way because it’s the preferred MVC paradigm, and you can just add properties for any additional fields you need to capture (and can take advantage of validation easily by just adding attributes).
Define a new view model:
Create the action in your controller:
2) Parameter bind a list of strings named
resourcesdirectly in the action:It’s important to note that in the question, the view is creating checkboxes that will send the string value of all checked resources, not boolean values (as you might expect if you used the
@Html.CheckBoxhelper) indicating if each item is checked or not. That’s perfectly fine, I’m just pointing out why my answer differs.