我有一个 ajax 调用发布到控制器。
当我点击一个销售按钮时,一个提示允许用户输入他们想要销售的游戏名称,该名称保存在 Video Game Store 数据库中。
但是,当调用 SellFunction 时,我收到 404 错误。
这是 JavaScript 代码:
function SellFunction() {
var name = prompt('Please enter the game you are selling us:');
alert("Thank you for your business!");
var RandomID = Math.random
RandomID *= 20;
Math.floor(RandomID);
var GameObject = {VideoID: RandomID, Price: 20, Name: name } //now we have to basically just send something easy
//ajax post store name in video game model for the store
$.ajax({
type: "POST",
data: JSON.stringify(GameObject),
url: "index/videogamesale",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response != null && response.success) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
});
}
这是我收到的错误:404 错误
这是我的控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace VideoGameStore.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult VideoGameSale(VideoGame newgame)
{
using (var db = new VideoGameModel())
{
db.Games.Add(newgame);
db.SaveChanges();
foreach (var VideoGame in db.Games)
{
Console.WriteLine(VideoGame.Name);
}
return Json(new { success = true, responseText = "Your
message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
}
}
}
这是视频游戏模型代码:
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;
namespace VideoGameStore
{
public class VideoGameModel : DbContext
{
public DbSet<VideoGame> Games { get; set; }
}
public class VideoGame
{
public int VideoID { get; set; }
public int Price { get; set; }
public string Name { get; set; }
}
}
这是表的图片:dbo.VideoTD
我在网上搜索过,但问题仍然像以往一样难以捉摸。任何帮助将不胜感激。谢谢你。
我相信您应该将 ajax 请求更改为此,它会完美解决
$.ajax({
type: "POST",
data: JSON.stringify(GameObject),
url: "Home/VideoGameSale",
method: "POST",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response != null && response.success) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}});
路由器会将其映射到 Controller Home 和 Action VideoGameSale。由于您的操作 VideoGameSale 需要 HTTPPOST 请求,因此它会解决方法的原因:“POST”语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句