如果这是一个新手问题,我很抱歉,但有人能告诉我为什么不能将 var 的值设置为 C# 属性吗? 我正在尝试找到一种方法来使用该值来检索一些模型属性并进行计算....
@using System.Collections
@using System.Runtime.Serialization
@using CarRentalMVCApp.Models
@model CarRentalMVCApp.Models.Rentals
@functions {
public string selection { get; set; }
public decimal Price { get; set; }
}
@{
ViewBag.Title = "Create";
}
<script>
function select() {
var $el = $("#selectedCar");
var selected = $("#selectedCar option:selected").text();
$el.on("change", @selection = selected);
alert(@selection);
}
function Rental() {
var choice = select();
@foreach (var car in ViewData["availableCars"] as IEnumerable<Vehicles>)
{
if (selection != null && int.Parse(selection) == car.מספר_רכב)
{
Price = car.עלות_ליום_השכרה;
}
}
if (firstDay != null && lastDay != null) {
var rentalData = {
price: @Price,
firstDay: $("#beginRental").val(),
lastDay: $("#endRental").val()
}
alert(rentalData);
}
}
</script>
@selection 总是等于 0,我尝试用另一个 veriable 设置它,如下所示:
@selection = selected;
它仍然是 0!!!
我也不明白为什么如果涉及@符号我就不能使用任何类型的javascript变量,如果您有时间或链接来帮助的话,我会很感激的解释......
最佳答案
MVC View 只是模板; C# 和 JavaScript 之间不存在任何形式的互操作。相反,您的 C# 变量只会导致文本替换。因此,这些行:
$el.on("change", @selection = selected);
alert(@selection);
...只需采用 C# selection
值并执行替换即可。因此,如果在 C# 中将 selection
设置为 "foo"
,则输出的 JavaScript 为:
$el.on("change", foo = selected);
alert(foo);
即使有效,change
事件的事件处理程序语法也不正确。另外,您不能让 JavaScript 为 C# 属性赋值。相反,JavaScript 必须提交表单或执行 AJAX 请求,以将数据发送回服务器进行处理,并由 MVC Controller 进行处理。
关于javascript - 在 MVC View 中使用 C# 属性时未设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937444/