How to send js variables to mvc controller

前端 未结 2 1609
故里飘歌
故里飘歌 2020-12-09 06:54

I`m new to client-server programming concepts. What I need, to send four js vars to my MVC 3 controller action.

    $(document).ready(function() {
        va         


        
相关标签:
2条回答
  • 2020-12-09 07:37

    Here goes solution -

    Model -

    public class ImageCoordinates
    {
        public int x1 { get; set; }
        public int x2 { get; set; }
        public int y1 { get; set; }
        public int y2 { get; set; }
    }
    

    Action -

        public ActionResult CreateCover(ImageCoordinates coordinates)
        {
            return null;
        }
    

    Lets create a View which will make the AJAX call to the Action.

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    
    <script>
        function submitForm() {
    
            var model = new Object();
            model.x1 = 120;
            model.y1 = 240;
            model.x2 = 360;
            model.y2 = 480;
    
    
            jQuery.ajax({
                type: "POST",
                url: "@Url.Action("CreateCover")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ coordinates: model }),
                success: function (data) {
                    alert(data);
                },
                failure: function (errMsg) {
                    alert(errMsg);
                }
            });
        }
    </script>
    
    <input type="button" value="Click" onclick="submitForm()" />
    

    Output -

    enter image description here

    0 讨论(0)
  • 2020-12-09 07:55

    Try changing the name of the object passed to the controller:

    $.ajax({
        url: '/dashboard/createcover',
        type: 'POST',
        data: {coordinates : JSON.stringify(myData)}, //change here
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data.success);
        },
        error: function () {
            alert("error");
        },
        async: false
    });
    

    Please note that this will post the values as a JSON object. You need to modify your controller like so:

    public ActionResult CreateCover(string jsonCoordinates) {
        ImageCoordinates coordinates = JsonConvert.DeserializeObject<ImageCoordinates >(jsonCoordinates);
    
        ViewData.Model = coordinates;
        return View();
    }
    

    You also need to add a reference to Newtonsoft.Json.

    0 讨论(0)
提交回复
热议问题