Gal Ratzkin Gal Ratzkin - 3 months ago 10
C# Question

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 a c# property ?
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 = selected;


it remains 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 .....

Answer

You cannot set a C# variable value in your client side code like the way you tried. 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).

So if you need to use this in your server code, you need to make an ajax call and send it to server

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.

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

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);
}