我正在尝试创建 asp.net mvc 应用程序。在 worker.cs 类中,我添加了这些参数:
public class Worker
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public double Net { get; set; }
[Editable(false)][NotMapped]
public double Gross
{
get {
if (Net <= 282.10 && Net > 0)
return Math.Round(Net / 0.91, 2);
else if (Net <= 335.30 && Net > 282.10)
return Math.Round((Net - 46.5) / 0.76, 2);
else if (Net <= 760 && Net > 335.3)
return Math.Round((Net - 75) / 0.685, 2);
else if (Net > 760)
return Math.Round((Net / 0.76), 2);
else
return 0;
}
}
}
Gross 参数应该是只读的。我的问题是关于编辑表单,我需要显示 gross 值,然后用户输入 net 值(实时)。我尝试使用 knockout.js,但我不能弄清楚该怎么做。
div class="form-group">
@Html.LabelFor(model => model.Net, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Net, new { htmlAttributes = new { @class = "form-control", data_bind = "value: NetV, valueUpdate:'afterkeydown'" } })
@Html.ValidationMessageFor(model => model.Net, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Gross, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Gross, new { @class = "form-control", data_bind="value:GrossV",@readonly = "readonly", disabled = "disabled" })
</div>
</div>
最佳答案
KnockoutJS 遵循 MVVM 结构,因此您可以将计算放在 View 模型中。
View 模型:-
var viewModel = function(data) {
var self = this;
self.net = ko.observable();
self.gross = ko.computed(function() {
if (self.net () <= 282.10 && self.net () > 0)
return parseFloat(self.net () / 0.91).toFixed(2);
else if (self.net () <= 335.30 && self.searchQuantity1 () > 282.10)
return parseFloat((self.net () - 46.5) / 0.76).toFixed(2);
else if (self.net () <= 760 && self.net () > 335.3)
return parseFloat((self.net () - 75) / 0.685).toFixed(2);
else if (self.net () > 760)
return parseFloat(self.net () / 0.76).toFixed(2);
else
return 0;
}, self);
};
ko.applyBindings(new viewModel());
查看:-
Net:-
<input id="test1" name="test1" type="text" data-bind="value: net, valueUpdate:'afterkeydown'"/>
<p>Gross: <span id="spantest3" data-bind="text: gross"></span></p>
参见 jsfiddle那个工作示例!!
希望它的工作!!
愉快的编码!!!
关于c# - 编辑表单中的 Asp.net mvc 计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609155/