Ajax发布到控制器404

时间:2017-05-14 13:10:41

标签: ajax asp.net-mvc entity-framework

我有一个ajax调用发布到控制器。

当我点击卖出按钮时,提示允许用户输入他们想要出售的游戏的名称,该名称保存在视频游戏商店数据库中。

但是,当调用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 Error

这是我的控制器代码:

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);

            }
        }

    }

}

以下是VideoGame型号代码:

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

我在网上搜索过,但问题仍然像以往一样难以捉摸。任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

我相信您应该将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和动作VideoGameSale。因为您的动作VideoGameSale需要一个HTTPPOST请求,所以它将使用方法:“POST”语句。