简体   繁体   English

在MVC视图中使用C#属性时未设置变量

[英]Variable not being set when using a C# property in an MVC view

i'm sorry if its a newbie question but can anyone tell me why can't I set a value of a var to ac# property ? 我很抱歉,如果这是一个新手问题,但是谁能告诉我为什么我不能将var的值设置为ac#属性? i am trying to find a way to use the value to retrieve some model properties & do a calculation .... 我试图找到一种使用该值来检索某些模型属性并进行计算的方法。

@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>

the @selection always equals 0 and ones I try to set it with another veriable like so: @selection始终等于0,我尝试用另一个veriable设置它,如下所示:

@selection = selected;

it remains 0 !!! 它仍然是0!

I also cant understand why I can't use any type of javascript variable if the @ sign is involved , would appresiate an explanation if you have the time or the links to help ..... 我也无法理解,如果涉及到@符号,为什么我不能使用任何类型的javascript变量,如果您有时间或可以提供帮助的链接,请给予解释。

MVC views are simply templates; MVC视图只是模板。 there is not any sort of interoperation between C# and JavaScript. C#和JavaScript之间没有任何形式的互操作。 Rather, your C# variables simply cause text replacement. 而是,您的C#变量仅导致文本替换。 Therefore, these lines: 因此,这些行:

$el.on("change", @selection = selected);
alert(@selection); 

...simply take the C# selection value and perform a substitution. ...只需获取C# selection值并执行替换。 So if selection is set to "foo" in the C#, the JavaScript that is output is: 因此,如果在C#中将selection设置为"foo" ,则输出的JavaScript为:

$el.on("change", foo = selected);
alert(foo); 

The event handler syntax for the change event is incorrect even if this did work. 即使该change事件起作用,事件处理程序的语法也不正确。 Plus, you cannot have JavaScript assign a value to a C# property. 另外,您不能让JavaScript将值分配给C#属性。 Rather, JavaScript will have to submit a form or perform an AJAX request to send data back to the server for processing, where it's handled by an MVC controller. 相反,JavaScript将必须提交表单或执行AJAX请求,以将数据发送回服务器进行处理,并由MVC控制器处理。

Short answer: The @ means that it's server code, not client code. 简短的答案:@表示它是服务器代码,而不是客户端代码。 It gets executed before the page is sent to the user. 在将页面发送给用户之前,它会执行。 Once the server finishes and the user gets the page, javascript code get executed. 服务器完成操作并且用户获得页面后,将执行javascript代码。

You cannot set a C# variable value in your client side code like the way you tried. 您不能像尝试的方式那样在客户端代码中设置C#变量值。 Because when razor executes, it executes the C# code in it ( at server ) and the result of that (which could be string) will be send to the client to render the markup needed for the page.(Check the view source of the page). 因为在执行razor时,它会在其中( 在服务器上 )执行C#代码,并将其结果(可能是字符串)发送给客户端以呈现页面所需的标记。(检查页面的视图源)。

So if you need to use this in your server code, you need to make an ajax call and send it to server 因此,如果您需要在服务器代码中使用此代码,则需要进行ajax调用并将其发送到服务器

So if you want the price of the selected item value, make an ajax call to your server and send the selected option value and using that calculate the price and return it. 因此,如果您希望所选商品价值的价格,请对服务器进行ajax调用,然后发送所选商品价值,然后使用该商品计算价格并将其返回。

var selected = $("#selectedCar option:selected").text();
$.get("@Url.Action("GetPrice","Home")"?id="+selected ,function(res){
    alert("Price of selection" + res);
});

Assuming GetPrice accepts a parameter with name id and returns the price 假设GetPrice接受名称为id的参数并返回价格

public ActionResult GetPrice(int id)
{
  // based on this id, Get the corresponding price
  decimal price = 100.0M; //replace with your value from db
  return Json(price,JsonRequestBehavior.AllowGet);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM