不确定这是否是正确的方法.但是,我在视图中有两个文本框,由控制器中的Viewbag填充.它们是int值.一个值是库存单位数(Viewbag.stock),另一个是订购单位数(Viewbag.ordered).我有第三个文本框,我
我尝试在控制器中执行此操作,但这并没有带来结果.我也试过在文本框的值中这样做,这也没有用.
这是我尝试完成此任务的第一种方式
模型
public int? OnHand { get; set; } public int? UnitsOrdered { get; set; }
调节器
ViewBag.Stock = r.FirstOrDefault().OnHand; ViewBag.Ordered = r.FirstOrDefault().UnitsOrdered; ViewBag.Total = ViewBag.Stock - ViewBag.Ordered;
视图
<div class="form-group"> @Html.LabelFor(model => model.UnitsOrdered, (string)"Units On Hand ", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBox("OnHand", null, new { @class = "form-control", Value = ViewBag.Stock, @readonly = "readonly" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.UnitsOrdered, (string)"Number of Units Ordered", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.UnitsOrdered, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } }) @ViewBag.MyCountIntro @ViewBag.MyCount @Html.ValidationMessageFor(model => model.UnitsOrdered, "", new { @class = "text-danger" }) </div> </div> <div class="col-md-10"> @Html.TextBox("Remaining", null, new { @class = "form-control", Value = ViewBag.Total, @readonly = "readonly" }) </div>
在上面的场景中,Viewbag.Stock是60.Viewbag.Ordered是2.Viewbag.Total应该是58.但相反,它是空白
我也尝试在视图中计算它本身.这也产生了空白.
<div class="col-md-10"> @Html.TextBox("Remaining", null, new { @class = "form-control", Value = ViewBag.Stock - Viewbag.Ordered, @readonly = "readonly" }) </div>ViewBag本身会将值视为对象.在进行计算之前,您应该将该对象强制转换为适当的类型.
ViewBag.Total =(int)ViewBag.Stock – (int)ViewBag.Ordered;