我无法让我的代码工作。我需要向我的控制器中的一个动作方法发送一个AJAX调用,该方法必须返回一个字符串(现在)。但是当我激活AJAX调用时,它会返回我当前所在页面的HTML源代码它甚至没有达到所需的控制器操作。
这是我的代码:
<script>
function addtoCart()
{
amount = prompt("Hoeveel producten wilt u toevoegen aan uw winkelwagen?", 1);
//find product
var product = {
"id": '@Model.ID',
"naam": "@Model.Naam",
"afbeelding": "@Model.Afbeelding",
"beschrijving": "@Model.Beschrijving",
"prijs": "@Model.Prijs",
"aantal": amount
};
$.ajax({
url: '@Url.Action("storeProductInSession", "Product")',
type: 'POST',
data: JSON.stringify(product),
dataType: 'json', //Right now, this gives an "Unexpected Token < error". This is probably because when the method returns the entire HTML document, it won't be able to render <!doctype html> as JSON.
contentType: 'application/json; charset=utf-8',
success: function (result)
{
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(product);
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
async: true
});
//sessionStorage.setItem('@Model.ID', JSON.stringify(product)); This is for later
}
[HttpPost]
public string storeProductInSession(object product)/*, string naam, string afbeelding, string beschrijving, decimal prijs, int aantal)*/
{
return "This method is going to do session stuff, but for now it just has to return this string";
//Get the POST input from the AJAX call
//Add the input to a JSON array
//add the array to the session
//Return the array
//let javascript convert that array to the cart <li>
}
它仍然返回整个HTML页面,即使object product
参数不正确,我也很高兴看到ajax调用实际上击中了该方法。我在想电话和路由之间可能存在问题,但我不确定。这是代码:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Product",
url: "Product/{id}",
defaults: new { controller = "Product", action = "Index" }
);
routes.MapRoute(
name: "Categorie",
url: "Categorie/{id}",
defaults: new { controller = "Categorie", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welkom", action = "Index", id = UrlParameter.Optional }
);
}
如果我甚至可以简单地将ID提供给StoreProductInSession操作,那么我可以从那里开始工作。我将使用用户的会话,所以我认为GET不够安全。
非常感谢@Dolan提供帮助!问题是我的路由!
<script>
function addtoCart()
{
amount = prompt("Hoeveel producten wilt u toevoegen aan uw winkelwagen?", 1);
//find product
var product = {
"id": '@Model.ID',
"naam": "@Model.Naam",
"afbeelding": "@Model.Afbeelding",
"beschrijving": "@Model.Beschrijving",
"prijs": "@Model.Prijs",
"aantal": amount
};
$.ajax({
url: '@Url.Action("storeProductInSession", "Product")',
type: 'POST',
data: JSON.stringify(product),
dataType: 'html', //I tried entering 'json' but that gave me a 'unexpected < token' error.
contentType: 'application/json; charset=utf-8',
success: function (result)
{
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(product);
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
async: true
});
</script>
[HttpPost]
public string storeProductInSession(int id, string naam, string afbeelding, string beschrijving, decimal prijs, int aantal)
{
return String.Format("Product given to the ajax call: {0}, {1}, {2}, {3}, {4}, {5}", id, naam, afbeelding, beschrijving, prijs, aantal);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Product",
url: "Product/{id}",
defaults: new { controller = "Product", action = "Index" },
constraints: new { id = "\\d+" }
);
routes.MapRoute(
name: "ProductAction",
url: "Product/storeProductInSession",
defaults: new { controller = "Product", action = "storeProductInSession" }
);
routes.MapRoute(
name: "Categorie",
url: "Categorie/{id}",
defaults: new { controller = "Categorie", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welkom", action = "Index", id = UrlParameter.Optional }
);
}
答案 0 :(得分:2)
您应该使用URL帮助程序:
url: '@Url.Action("storeProductInSession", "Product")',
有关详细信息,请参阅here。
好的,我认为您的产品对象存在问题。它不是一个对象,而是一个字符串。 &#39;产品对象周围的字符是问题 - JavaScript认为它是一个字符串 - 而不是一个对象。它应该是这样的:
var product = {
"id": "@Model.ID",
"naam": "@Model.Naam",
"afbeelding": "@Model.Afbeelding",
"beschrijving": "@Model.Beschrijving",
"prijs": "@Model.Prijs",
"aantal": " + amount + "
};
见这里:http://jsfiddle.net/donal/mo776xe0/1/
另外,如果你知道id是一个整数,你可以这样做:
var product = {
"id": @Model.ID,
"naam": "@Model.Naam",
"afbeelding": "@Model.Afbeelding",
"beschrijving": "@Model.Beschrijving",
"prijs": "@Model.Prijs",
"aantal": " + amount + "
};
你可以试试这个:
[HttpPost]
public string storeProductInSession(object product)
{
return "This method is going to do session stuff, but for now it just has to return this string";
}
看看你的路线,我可以看到问题。
假设storeProductInSession是您要查找的产品的ID,因此转到Product控制器的Index操作。
我们需要的是约束。如果id是数字(数字),则约束将告知路由仅使用它。例如:constraints: new { id = @"\d+" }
因此,您需要将路由更改为此(您还需要Product / storeProductInSession操作的路由):
routes.MapRoute(
name: "Product",
url: "Product/{id}",
defaults: new { controller = "Product", action = "Index" },
constraints: new { id = "\\d+" }
);
routes.MapRoute(
name: "ProductAction",
url: "Product/storeProductInSession",
defaults: new {controller = "Product", action = "storeProductInSession"}
);
routes.MapRoute(
name: "Categorie",
url: "Categorie/{id}",
defaults: new { controller = "Categorie", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welkom", action = "Index", id = UrlParameter.Optional }
);
因此,当您要求Product / storeProductInSession时。它将看到storeProductInSession不是数字,然后转到下一个路线。
下一个路由将指向Product控制器和storeProductInSession操作。
答案 1 :(得分:0)
试试这个,删除&#34; dataType:html&#34;并改变这个:( echo而不是返回):
[HttpPost]
public string storeProductInSession(int id, string naam, string afbeelding, string beschrijving, decimal prijs, int aantal)
{
echo "This method is going to do session stuff, but for now it just has to return this string";
}