我的ajax调用应该怎么样--jQuery,MVC4?

时间:2017-05-19 11:55:57

标签: javascript jquery ajax asp.net-mvc-4 c#-4.0

这是我在Visual Studio 2010中使用向导创建的Api Controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using ApiTest2MvcApplication.Models;
using System.Linq.Expressions;
using ApiTest2MvcApplication.DTOs;
using System.Threading.Tasks;
using System.Web.Http.Description;
using System.Web.Mvc;

namespace ApiTest2MvcApplication.Controllers
{
    public class Default1Controller : ApiController
    {
        private UsersContext db = new UsersContext();

        // GET api/Default1
        public IEnumerable<UserProfile> GetUserProfiles()
        {
            return db.UserProfiles.AsEnumerable();
        }

        // GET api/Default1/5
        public  UserProfile GetUserProfile(int id)
        {
            UserProfile userprofile = db.UserProfiles.Find(id);
            if (userprofile == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return userprofile;
        }


        // PUT api/Default1/5
        public HttpResponseMessage PutUserProfile(int id, UserProfile userprofile)
        {
            if (ModelState.IsValid && id == userprofile.UserId)
            {
                db.Entry(userprofile).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        // POST api/Default1
        [AcceptVerbs("POST")]
        public HttpResponseMessage PostUserProfile(UserProfile userprofile)
        {
            System.Diagnostics.Debug.WriteLine("Username: " + userprofile.UserName);
            if (ModelState.IsValid)
            {
                db.UserProfiles.Add(userprofile);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, userprofile);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = userprofile.UserId }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        // DELETE api/Default1/5
        public HttpResponseMessage DeleteUserProfile(int id)
        {
            UserProfile userprofile = db.UserProfiles.Find(id);
            if (userprofile == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.UserProfiles.Remove(userprofile);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK, userprofile);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

这是我的jQuery ajax调用视图:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<input type="button" id="postBtn" value="Post"/>
<script src="../../Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    var testPost = (function () {
        return {
            usePost: function (e) {
                //e.defaultPrevented();
                $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    method: "POST",
                    url: "/api/Default1",
                    data: { UserId: 1000, UserName: "Vlado", Email: "vlado@mysite.com", Phone: "(02) 1212121", NameAndSurname: "Vlade Edalv" },
                    dataType: "json",
                    beforeSend: function (jqXHR, settings) {
                        console.log("Sending data...");
                    },

                    success: function (data, textStatus, jqXHR) {
                        console.log("status: " + textStatus + ", data: " + JSON.stringify(data));
                    },

                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log("Status: " + textStatus + ", Error: " + errorThrown);
                    }
                });
            },

            pageReady: function () {

            }
        };
    } ());

    $.ready(testPost.pageReady);
    $("#postBtn").on('click', testPost.usePost);
</script>

我面临的问题是,在浏览器网络选项卡中,我看到此调用仍在使用GET方法而不是POST,因此我将UserProfile表中列出的所有数据作为对此GET请求的响应。

我知道问题在于路由,但我不知道在哪里添加以及添加什么。有人可以告诉我如何使用我的Api控制器POST方法吗?

1 个答案:

答案 0 :(得分:2)

使用type:而不是方法。不推荐使用AFAIK方法。