从razor中的javascript访问对象

时间:2017-12-13 16:48:55

标签: javascript c# razor asp.net-core-mvc

我需要在应用程序周围移动此对象而不会丢失它。起初,我只是使用静态类来完成它,这很简单,快速和有效。但是,我注意到任何人都可以从任何地方访问静态对象。因此,由于这是一个严重的安全风险,我一直试图找到另一种方式来做到这一点。我已经提出了一个ajax请求,要求在后面的代码中做必要的事情(在这种情况下,将是预订酒店的新房间)。都好。问题是,我想再次将它带回客户端,模型或其他东西,以便在我需要预订另一个房间时使用它。截至目前,我单击“预订”按钮,它会添加一个房间,但一旦返回到客户端,对象就会丢失。所以,我在服务器端将其序列化并将其返回给服务器端。但后来我无法使用剃刀代码访问它。

我不知道是否可以这样做(至少这样)。但必须有另一种方式,因为许多网站必须进行销售,例如,切换页面并保留所有信息。如果可能的话,我想避免不得不一直去数据库这样做。我想把它留在记忆中。

所以,要显示代码:

<button type="reset" class="btn btn-info center-block" onclick='BookRoom(
      @Html.Raw(Json.Serialize(Model)),                                                
      "@Repository.RoomTypeList[i].UUID",
      "@Repository.RoomTypeList[i].PossibleRateTypes[j].UUID",
      "checkIn",
      "checkOut");'>
       Book
</button>

<script type="text/javascript">
    function AjaxRooms(URL, method, contentType, request, dataType, successRespMsg, successRespObj) {
        $.ajax({
            url: URL,
            method: method,
            contentType: contentType,
            data: JSON.stringify(request),
            dataType: dataType,
            success: function (resp) {
                debugger
                alert(resp[successRespMsg]);
                var aux = JSON.parse(resp[successRespObj]);

                // Here is where I want to access the object from javascript to razor, in order to keep it in memory

            },
            error: function (error) {
                alert(error);
            }
        })
    }

function BookRoom(model, roomUUID, rateUUID, checkIn, checkOut) {
    AjaxRooms('Home/Book?ro=' + roomUUID + '&ra=' + rateUUID + '&ci=' + document.getElementById(checkIn).value + '&co=' + document.getElementById(checkOut).value,
            'post', 'application/ json', model, 'json', 'msg', 'obj');    
}
</script>



public class Reservation
{
    public DateTime CheckIn { get; set; }
    public DateTime CheckOut { get; set; }

    public List<RoomType> BookedRooms { get; set; } = new List<RoomType>();
}

    public IActionResult Book([FromBody]Reservation reservation)
    {
        var roomUUID = HttpContext.Request.Query["ro"].ToString();
        var rateUUID = HttpContext.Request.Query["ra"].ToString();
        var checkIn = HttpContext.Request.Query["ci"].ToString();
        var checkOut = HttpContext.Request.Query["co"].ToString();

        try
        {
            if (checkIn == "" || checkOut == "")
                return Json(new { msg = "You have to select a Check In and a Check Out date.", obj = JsonConvert.SerializeObject(reservation) });
            else if (roomUUID != "" || rateUUID != "")
            {
                // Adds a new room (with the specified rate) to the list
                var roomType = Repository.DeepClone(Repository.RoomTypeList)
                    .FirstOrDefault(r => r.UUID == roomUUID);

                roomType.PossibleRateTypes = new List<RateType>() { roomType.PossibleRateTypes.FirstOrDefault(rt => rt.UUID == rateUUID) };

                reservation.BookedRooms.Add(roomType);
                reservation.CheckIn = Convert.ToDateTime(checkIn);
                reservation.CheckOut = Convert.ToDateTime(checkOut);

                return Json(new { msg = "Added to cart.", obj = JsonConvert.SerializeObject(reservation) });
            }
            else
                return Json(new { msg = "We couldn't add it to cart. Please try again.", obj = JsonConvert.SerializeObject(reservation) });

        }
        catch (Exception ex)
        {
            return Json(new { msg = "An error has occurred. Please try again later or contact and administrator.", obj = JsonConvert.SerializeObject(reservation) });
        }
    }

我一直在这样做,但你可以提出另一种更好的方法来做到这一点。我听见了。

1 个答案:

答案 0 :(得分:1)

您是否考虑在浏览器中使用local/session存储空间?当用户在您的网站上从一个页面跳转到另一个页面时,这将是将数据保留在内存中的一种方法。