将Ajax调用中的值传递给索引方法

时间:2017-08-22 20:24:18

标签: ajax entity-framework asp.net-mvc-5 controller

我有一个要求,我要将Ajax调用的id返回到'HomeController'的Index方法,我可以使用Ajax将id传递给控制器​​,如下所示:

更新1

ProductRating Class

public class ProductRating
{
   public int ProductId { get; set; }
   public string ProductName { get; set; }
   public double UserRating { get; set; }
   public double? RatingCount { get; set; } //Messed up with this earlier and when Luqman told me about the model, it reminded to add this property and the rest is done 
   public double? Total { get; set; }
}

Ajax Call

<script>
$(document).ready(function (response) {
     if (response) {
       $.ajax({
          url: '@Url.Action("AddRating")',
          data: { id: '@item.ProductId', rating: rate },
          type: 'POST',
          success: function (data) {
                 $('.@item.ProductId').html(data);
                   }
                });
              }
          }).fail(function () {
        alert("Failed to get total ratings!");
     });
</script>

控制器

[HttpPost]
public JsonResult AddRating(int id, double rating)
{
   var con = new ProductRating
   {
      RatingCount = db.Ratings.Where(c => c.ProductId == id).Count()
   };

   if (con.RatingCount >= 300)
   {
      return Json("Rating limit already exits", JsonRequestBehavior.AllowGet);
   }
   else
   {
      Ratings aRatings = new Ratings();
      aRatings.ProductId = id;
      aRatings.UserRating = rating;

      db.Ratings.Add(aRatings);
      db.SaveChanges();

      return Json(con.RatingCount, JsonRequestBehavior.AllowGet);
   }
}

参见上面的方法,我将id设置为会话变量,并将此变量值作为参数传递给Index方法。问题是在刷新页面之前,会话变量在第一次尝试时不起作用。但是在调试时,我可以看到值,每次都会被删除。我想,这不是正确的方法。 ViewBagSession似乎没有帮助。我的要求是计算单个产品对其产品ID的评级,并且应该使用相同的Ajax调用返回。在Index方法中,我正在执行以下操作:

CountAll = db.Ratings.Where(c => c.ProductId == id).Count() //id - I am trying to pass from Ajax call

我希望,有更好的方法可以做到这一点,并且目前正在努力解决这个问题。

注意:感谢@Luqman和@Stephen Muecke。 @Stephen Muecke感谢您的来电。我正在为演示目的制作两个Ajax调用,并为延迟更新帖子道歉。

现在是工作样本:

Star Rating

1 个答案:

答案 0 :(得分:1)

为什么使用会话来存储id。请使用Model或Tempdata存储该ID。