[英]MVC passing from view to controller data outside of the view model
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.
我希望它以这种方式工作,即当选中它时,控制器将把startDate设置为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? 有没有办法以这种方式传递参数?
If the value of your checkbox is bool, you can do something like this: 如果您的复选框的值是bool,则可以执行以下操作:
<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. 如果不想使用隐藏输入,则可以使操作中的bool参数为可空,并将null视为false。
public async Task<ActionResult> AddAuction(Auctions auction, bool? gm = null)
{
if(gm == null)
gm = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.