Ajax.ActionLink repeating the same exact GET request multiple times
I'm learning MVC and am currently making a simple SCRUM tracking system as I go along.
The problem I'm having is that when an Ajax.ActionLink is clicked, I run the same ajax action once for every scrum card displayed on the page.
As you can see, I have 9 cards displayed and I get 9 identical GET requests. (The action link is actually the color wheel image in the lower right hand side of the card).
SingleCard.cshtml (View) - "ColorPicker" is the name of my action.
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
...
<div class="card_footer" id="card_footer_id_@(Model.ID)">
<div class="card_tags">
[Tag1] [Tag2] [Tag3]
</div>
<div class="card_colorwheel_icon">
@Ajax.ImageActionLink("../Content/Images/color_wheel.png", "Color Wheel", "ColorPicker", new { cardid = Model.ID }, new AjaxOptions { UpdateTargetId = "ColorPickerDisplay" })
</div>
</div>
The ImageActionLink is a helper I'm using, but it works exactly like the normal ActionLink
HomeController.cs (Controller)
public ActionResult ColorPicker(int cardid)
{
var currentcard = db.Cards.Single(x => x.ID == cardid);
var colors = new List<CardRGB>();
var cards = db.Cards.ToList();
foreach (var card in cards)
{
colors.Add(new CardRGB
{
CardId = card.ID,
Red = (int)card.BG_Red,
Blue = (int)card.BG_Blue,
开发者_StackOverflow中文版 Green = (int)card.BG_Green
});
}
// disctint
var model = new ColorPickerViewModel()
{
Colors = colors,
Red = (int) currentcard.BG_Red,
Green = (int) currentcard.BG_Green,
Blue = (int) currentcard.BG_Blue
};
return PartialView(model);
}
Does anyone know why this code is running once per card?
EDIT: As requested!
public static class ImageActionLinkHelper
{
public static MvcHtmlString ImageActionLink(
this AjaxHelper helper,
string imageUrl,
string altText,
string actionName,
object routeValues,
AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", altText);
builder.MergeAttribute("title", altText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
var html = link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
return new MvcHtmlString(html);
}
}
Check the HTML of your page. In your singlecard.cshtml there is the line:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
For every card again you include the javascript, so it is included 9 times. Therefore 9 requests will be sent to the server.
Solution: put the script-include on page level, not on card level.
精彩评论