私は、Ajax呼び出しからのidを `HomeController 'のIndexメソッドに返す必要があり、次のようにAjaxを使ってidをコントローラに渡すことができます:Ajaxから値を渡す方法インデックスメソッド
アップデート1:
ProductRatingクラス:
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のコール:
<script>
$(document).ready(function (response) {
if (response) {
$.ajax({
url: '@Url.Action("AddRating")',
data: { id: '@item.ProductId', rating: rate },
type: 'POST',
success: function (data) {
$('[email protected]').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メソッドには、この変数の値を渡します。問題は、ページを更新するまでセッション変数が最初の試行で機能しないことです。しかし、デバッグしている間、私は値を見ることができ、毎回、それは消去されます。私はそうする正しい方法ではないと思います。 ViewBag
とSession
は役に立たないようです。私の要件は、個々の製品の評価をその製品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お電話いただきありがとうございます。私はデモの目的と謝罪のために2回Ajaxの呼び出しを行い、投稿の更新を遅らせました。ここで
は今働いサンプルです:あなたがIDを保存取得するためにセッションを使用する理由
なぜ2つの別々のajaxコールを作成していますか? –
更新された投稿@Stephen Mueckeをご覧ください。ありがとう、 –