执行操作而不重定向(添加到愿望列表)



所以,我有一些产品卡,我用foreach循环显示。当我点击链接时,我想将该产品添加到我的愿望列表(会话["愿望列表"](。它调用一个函数并将我重定向到/product/wwishlist/01,其中01是产品id。

我的临时修复程序是return Content("<script type='text/javascript'>window.history.back();</script>");,但不重新加载会更好。

我的代码:

<code>
<a href="@Url.Action("AddToWishList", "Product", new {id = item.Id})"><i class="far fa-heart"></i></a>
</code>

控制器:

<code>
public ActionResult AddToWishList(int id)
{
if (Session["email"] != null && Session["role"] != null && (WebApplication1.Models.RoleType)Session["role"] == Models.RoleType.User)
{
var wishList = (List<int>)Session["wishList"];
if (wishList.Contains(id))
{
wishList.Remove(id);
}
else
{
wishList.Add(id);
}
Session["wishList"] = wishList;
}
return Content("<script type='text/javascript'>window.history.back();</script>");
}</code>

您可以在您的案例中使用Ajax,它用于更新页面的一部分,而无需重新加载整个页面。在您的情况下,您可以执行以下操作:

定义一个函数,该函数将采用所选元素的id

<code>
<a href="#" onClick='addToWishList('@item.Id')'><i class="far fa-heart"></i></a>
</code>

然后,您需要定义一个函数,该函数将接受此id并通过Ajax:将其发送到您的Controller

<script>
function addToWishList(id)
{
var json = {
id : id
}; 

$.ajax({
type: 'POST',
url: "@Url.Action("AddToWishList", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function(data) {
if(data.status=="true")
{
alert(data.msg);
var urlToRedirect= '@Url.Action("Index","Home")';
window.location.href = urlToRedirect; //Redirect here
}
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
</script>

最后,在您的Controller中,您可以处理这个id,然后返回一个结果:

using System.Web.Script.Serialization;
[HttpPost]
public ActionResult AddToWishList(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id = Convert.ToInt32(jsondata["id"]);
if (Session["email"] != null && Session["role"] != null && (WebApplication1.Models.RoleType)Session["role"] == Models.RoleType.User)
{
var wishList = (List<int>)Session["wishList"];
if (wishList.Contains(id))
{
wishList.Remove(id);
}
else
{
wishList.Add(id);
}
Session["wishList"] = wishList;
}

return Json(new {status="true", msg= "Successfully processed"});
}

你可以根据自己的要求定制方法。

在页面中实现回调可以工作:

  • ASP网络:https://learn.microsoft.com/en-us/previous-versions/aspnet/ms366518(v=对100(
  • ASP.Net MVC:https://docs.devexpress.com/AspNetMvc/9052/common-features/callback-based-functionality

最新更新