会话变量默认为最后一个集合



我知道这是我的做法不好,但我仍然想了解为什么这不起作用。

我在 Javascript 中为不同的网格提供了 3 种onclick方法:

$('body').on('click', '#clinician-appointments>tbody>tr>td:not(:last-child):not(:first-child)', function () {
var id = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
@{Session["Clinician"] = "opa"};
location.href = "@Url.Action("Summary", "Patient")" + "/" + id;
});
$('body').on('click', '#clinician-current-admissions>tbody>tr>td:not(:last-child):not(:first-child)', function () {
var id = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
location.href = "@Url.Action("Summary", "Patient")" + "/" + id;
@{Session["Clinician"] = "ca"};
});
$('body').on('click', '#clinician-diagnostics>tbody>tr>td:not(:last-child):not(:first-child)', function () {
var id = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
location.href = "@Url.Action("Summary", "Patient")" + "/" + id;
@{Session["Clinician"] = "diag"};
});  

但是,当我在 C# 中调用会话时,它始终是"diag",即最后一个分配的会话。

因此,由于它们处于不同的事件中,因此将错过其他事件。

由于这是一个 Razor 页面,当您执行以下操作时:

@{Session["Clinician"] = "diag"};

这将在浏览器中呈现页面之前执行。因此,当页面加载时,将按顺序在服务器端执行以下内容:

@{Session["Clinician"] = "opa"};
@{Session["Clinician"] = "ca"};
@{Session["Clinician"] = "diag"};

与您的期望相反,它们不会在单击相应的网格时执行,因为这是一个纯粹的客户端交互事件。

我建议您将"@{Session["Clinician"] = "..."};"替换为对在会话中设置字符串的新控制器操作的 ajax 调用。所以像这样:

JavaScript:

function Session()
{
}
Session.SetString = function (key, value)
{
$.post("/Home/SessionString?key=" + key + "&value=" + value);
};
Session.GetString = function (key, successCallback)
{
$.get("/Home/SessionString?key=" + key, null, function (data, textStatus, jqXHR) { successCallback(data) });
};
$('body').on('click', '#clinician-appointments>tbody>tr>td:not(:last-child):not(:first-child)', function () {
var id = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
Session.SetString("Clinician", "opa");
location.href = "@Url.Action("Summary", "Patient")" + "/" + id;
});

控制器(适用于 .NET Core(:

/// <summary>
/// Sets a value in the user's session.
/// </summary>
/// <param name="key">The key for the value.</param>
/// <param name="value">The value.</param>
[HttpPost]
public IActionResult SessionString(string key, string value)
{
HttpContext.Session.SetString(key, value);
return new JsonResult(null);
}
/// <summary>
/// Get a value from the user's session.
/// </summary>
/// <param name="key">The key for the value.</param>
/// <returns>The value.</returns>
[HttpGet]
public IActionResult SessionString(string key)
{
string value = HttpContext.Session.GetString(key);
return new JsonResult(value);
}
}

最新更新