Answer the question
In order to leave comments, you need to log in
Why can't send ajax request?
I want the InitialFavorite method to run when the site loads, but I don't understand why it doesn't.
Script on the master page
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@section scripts{
<script type="text/javascript">
$(document).ready(function () {
$.get('@Url.Action("InitialFavorite", "Home")')
});
</script>
}
public void InitialFavorite()
{
if (User.Identity.IsAuthenticated)
{
var user = db.Users.FirstOrDefault(u => u.LogIn == User.Identity.Name);
var favorites = db.FavoriteRealties.Where(f => f.UserId == user.Id).ToList();
if (favorites != null)
{
foreach (var f in favorites)
{
foreach (var r in db.Realties)
{
if (f.RealtyId == r.Id && f.UserId == user.Id)
{
r.isFavorite = true;
}
else
{
r.isFavorite = false;
}
}
}
db.SaveChanges();
}
}
}
public void toogleFavorite(int id)
{
var user = db.Users.FirstOrDefault(u => u.LogIn == User.Identity.Name);
if (user != null) {
var favorites = db.FavoriteRealties.Where(f => f.UserId == user.Id).ToList();
if (favorites != null) {
var existFR = favorites.FirstOrDefault(fr => fr.RealtyId == id);
if (existFR == null)
{
db.FavoriteRealties.Add( new FavoriteRealties { RealtyId = id, UserId = user.Id });
}
else
{
db.FavoriteRealties.Remove(existFR);
}
var r = db.Realties.FirstOrDefault(rl => rl.Id == id);
r.isFavorite = !r.isFavorite;
}
else if (favorites == null)
{
db.FavoriteRealties.Add(new FavoriteRealties { UserId = user.Id, RealtyId = id });
db.Realties.FirstOrDefault(r => r.Id == id).isFavorite = true;
}
db.SaveChanges();
}
return;
}
Answer the question
In order to leave comments, you need to log in
Here you are passing an incorrect address:
You are passing a line of code, but you need a specific link.
$.get('@Url.Action("InitialFavorite", "Home")')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question