我想将java scrip var保存到asp.net mvc Temp-data但是它给出了语法错误
$(".PopReviewNo").click(function () {
if (($('textarea').val().length == 0)) {
$('.comm').addClass("layout");
}
else {
$(".comm").removeClass("layout");
var comment = $("#comme").val();
**@TempData["CommentForPop"]= $("#comme").val();** ///Check this one
$.fancybox({
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'easingIn': 'easeOutBack',
'easingOut': 'easeInBack',
'width': 850,
'height': 394,
href: "/Stores/PopReview/@Model.Company.id?comment=" + comment,
'type': 'iframe'
});
}
});
答案 0 :(得分:2)
您可以这样做,将数据发送到端点以进行保存:
$(".PopReviewNo").click(function () {
if (($('textarea').val().length == 0)) {
$('.comm').addClass("layout");
}
else {
$(".comm").removeClass("layout");
var comment = $("#comme").val();
var myVariableToSave = $("#comme").val();
//Send the variable to be saved
$.getJSON('@Url.Action("myendpoint")', { dataToSave: myVariableToSave}, function(data) {
//show a message if you want
});
$.fancybox({
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'easingIn': 'easeOutBack',
'easingOut': 'easeInBack',
'width': 850,
'height': 394,
href: "/Stores/PopReview/@Model.Company.id?comment=" + comment,
'type': 'iframe'
});
}
});
请记住TempData意味着请求之间存在持久性,因此将在请求结束时清除。因此,请为您的变量寻找其他存储空间。
public ActionResult MyEndPoint(string dataToSave)
{
if(string.IsNullOrEmpty(dataToSave))
{
return Json(new { message = "Empty data to save"}, JsonRequestBehaviour.AllowGet);
}
//Save it to session or some other persistent medium
Session["dataToSave"] = dataToSave;
return Json(new { message = "Saved"}, JsonRequestBehaviour.AllowGet);
}
您还可以执行ajax帖子而不是获取和检查表单令牌,以提高安全性,例如建议的here。
答案 1 :(得分:1)
我尝试使用gdp的答案,但却继续在路径中找到非法字符"。 相反,我修改了一点使用AJAX:
$(".PopReviewNo").click(function () {
if (($('textarea').val().length == 0)) {
$('.comm').addClass("layout");
}
else {
$(".comm").removeClass("layout");
var comment = $("#comme").val();
var myVariableToSave = $("#comme").val();
$.ajax({
// alert(myVariableToSave); // Check the value.
type: 'POST',
url: '/mycontroller/myendpoint',
data: "dataToSave=" + myVariableToSave,
success: function (result) {
//show a message if you want
},
error: function (err, result) {
alert("Error in assigning dataToSave" + err.responseText);
}
$.fancybox({
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'easingIn': 'easeOutBack',
'easingOut': 'easeInBack',
'width': 850,
'height': 394,
href: "/Stores/PopReview/@Model.Company.id?comment=" + comment,
'type': 'iframe'
});
}
});
和我的行动:
public ActionResult myendpoint(string dataToSave)
{
if (string.IsNullOrEmpty(dataToSave))
{
return Json(new { message = "Empty data to save" }, JsonRequestBehavior.AllowGet);
}
//Save it to session or some other persistent medium
...
//return Json(new { message = "Success" }, JsonRequestBehavior.AllowGet);
// or
return new EmptyResult();
}
我不相信这一点,如果不是@gdp,我就不会想到这个方向