简体   繁体   中英

Error sending data with Ajax and receiving in controller

I am sending Json data but when I verify my method in my controller it arrives as null

html:

<div class="hijo">
                    @Html.LabelFor(m => m.Proyecto, new { @class = "", style = "color:#040404" })
                    @Html.DropDownListFor(Model => Model.ProyectoID, Model.Proyecto, "Seleccionar")
                    @Html.ValidationMessageFor(Model => Model.Proyecto, null, new { @class = "label label-danger", id = "Proyecto" })
                </div>
<div class="hijo">
                    <input type="button" id="adicionar" value="Agregar" class="myButton">
                </div>

JS:

$('#adicionar').click(function () {
        debugger;
        var data= {
        Proyecto: $("#ProyectoID option:selected").text()
    };
    $.ajax({
        url: "../ManejoDatos",
        type: "POST",
        dataType: "json",  
        data: JSON.stringify(data),
        success: function (mydata) {
            $("#UpdateDiv").html(mydata);
            history.pushState('', 'New URL: ' + href, href); // This Code lets you to change url howyouwant
        }
    });
 }

My Controller

public JsonResult ManejoDatos(string Proyecto)
    {
         ........
         ...
        return Json(Proyecto);
    }

Console

在此处输入图片说明

I don't know if it's something very simple to fix but I don't see the error

regards

I found your JavaScript code is absolutely fine. The weird things is controller with your format ghostly doesn't work But I got success below way:

        [System.Web.Http.HttpPost]
        public HttpResponseMessage ManejoDatos(string Proyecto)
        {
            var data = " my test data ";
            return Request.CreateResponse(HttpStatusCode.OK, data);
        }

I will investigate that obviously and update the answer again .

Hope above idea help you to resolve your problem. Let me know if you encounter any more problem.

Simple types like string,int,float etc are to be fetched from query string in .Net framework where as complex types always fetched from body.

Solution-1

In this case .Net Framework is expecting string Proyecto from query parameters and you can call your API like this without making any change to your server side code

Note:Also you don't need to define key of the parameter (in http request) which is being defined as [From Body] . As total of one simple type can be passed using [FromBody] attribute which you can see below like this =ProyectoValue

POST ../ManejoDatos HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded
=ProyectoValue

Solution-2

Or you can call your API by putting all your params in complex model and pass params through body instead of query parameters like this

Complex Type Model

public class MyModel
    {
        public string Proyecto{ get; set; }
    }

API Code

public JsonResult ManejoDatos(MyModel myModel)
    {
         //Access using mymodel.Proyecto
         ........
         ...
        return Json(mymodel.Proyecto);
    }

And now you can consume your API by passing paramters through body like this

POST ../ManejoDatos HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded

proyecto=myproyecto

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