简体   繁体   中英

How should my ajax call look like - jQuery, MVC4?

Here is my Api Controller I created using the wizard in Visual Studio 2010:

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

And here is my View with jQuery ajax call:

@{
    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>

The problem I face is, in browser network tab I see this call is still using the GET method instead of POST, so I get all the data that is listed in UserProfile table as a response to this GET request.

I know that the problem is routing, but I don't know where to add and what to add. Can somebody tell me how to use my Api controller POST method?

Use type: instead of method. AFAIK method is deprecated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM