4

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() {
        var $jcrop;

        $('#image').Jcrop({
            bgColor: 'red',
            onSelect: refreshData
        }, function () {
            $jcrop = this;
        });

        function refreshData(selected) {
            myData = {
                x1: selected.x1,
                x2: selected.x2,
                y1: selected.y1,
                y2: selected.y2
            };
        }
    });

So i get my vars in browser.

What I have on server side is:

    public ActionResult CreateCover(ImageCoordinates coordinates) {
        ViewData.Model = coordinates;
        return View();
    }

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

Is there an easy way to post my four params from js to my action? I tried to use couple examples from this site, using $.ajax

Like this

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

But it does not worked, i received 0 0 0 0 in my action. But honestly I`m not even sure how to call this jquery function. Should i call it by clicking the button, or it auto calls when i post the form? And are there other methods to send this params?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

5 Comments

highlight the most important part "data: JSON.stringify({ coordinates: model }),"
Thank you, i tested this,and i recieved variables at my controller action. An additional question is, how to render another view with my recieved params.
public ActionResult CreateCover(ImageCoordinates coordinates) { ViewData.Model = coordinates; return View(); } This is my view code, but i`m still at that page i sent my params. In debug i receive my vars in action,b ut the view does not render.
@CadmusX, I am glad you solved the problem. For additional questions, please post them as separate questions.
@ramiramilu I can get this working for one controller but is it possible to pass it to many controllers?
2

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.

8 Comments

Nah.. MVC got built in json model binder no need to Deserialize
@AlexanderTaran, I partially agree. If you play a little with passing dictionaries, you quickly reach the conclusion that some of the parsing must be explicitly done in the controller.
@AndreiV First thank you for your help and time. I tried to use your code, but recieved 500 sever error.
POST http://localhost:42771/dashboard/createcover 500 (Internal Server Error) jquery-1.7.1.min.js:4 send jquery-1.7.1.min.js:4 f.extend.ajax jquery-1.7.1.min.js:4 submitForm Imgedit:21 onclick How should i execute $.ajax function? I pasted it in submitForm() funk that called when button is clicked.
Does your action get hit? Do you see the values in your action when debugging?
|
0

In the situation that you don't want to use AJAX or want a quick work around you can also try adding a hidden field and then using Javascript(JS) to populate the value in that hidden field.

    @Html.HiddenFor(m=>Model.ImageCoordinates.x1)
    <button type="submit">Submit Coordinates</button>

This will generate an 'input' tag on the html side with an id ="ImageCoordinates_x1" Then using JS

function refreshData(selected) {
            myData = {
                x1: selected.x1,
                x2: selected.x2,
                y1: selected.y1,
                y2: selected.y2
            };
            return myData;
           
}

let coordinateData = refreshData(selected)
let x1 = document.getElementById("ImageCoordinates_x1");
x1.value = coordinateData .x1;

You are now able to send the x1 coordinate information to the server through this. To send data to the other coordinates you will have to create hidden forms for them and populate the value of the input tag using JS

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.