Reputation: 2733
I have an interface for creating Auctions on an auction website.
@using (Html.BeginForm("AddAuction", "Auction", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.title, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.title)
@Html.ValidationMessageFor(model => model.title)
</div>
</div>
(...) some other fields
<div class="form-group">
@Html.LabelFor(model => model.startDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.startDate)
@Html.ValidationMessageFor(model => model.startDate)
<input type="checkbox" id="gm" name="gm" value="Now" onclick=""> Now<br>
</div>
</div>
(...) some other fields (...)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
}
The problem I have is with the checkbox "Now". I want it to work in such way that when it is checked, the controller will just set the startDate to DateTime.Now. Unfortunately, I don't know if there's any way of passing the value of the checkbox to the controller without editing the model. I am looking for something like:
public async Task<ActionResult> AddAuction(Auctions auction, **bool checked**)
Is there a way to pass the parameter in such way?
Upvotes: 0
Views: 1249
Reputation: 3543
If the value of your checkbox is bool, you can do something like this:
<input type="checkbox" id="gm" name="gm" value="True"> Now<br>
<input type="hidden" name="gm" value="False">
And in the controller
public async Task<ActionResult> AddAuction(Auctions auction, bool gm)
Checkboxes are only submitted if they are checked, that's why you will have to add a hidden input with the same name to submit a false value if checkbox is not checked.
If you do not want to use hidden input, then you can make bool parameter in the action nullable, and treat null as false.
public async Task<ActionResult> AddAuction(Auctions auction, bool? gm = null)
{
if(gm == null)
gm = false;
}
Upvotes: 2