1

I'm trying to get and pass my ViewModel to my Json method doing the stuff like this :

In my view :

<input type="button" id="suggestionBtn" title="Suggestion" onclick ="location.href='@Url.Action("GetNextAppointment", "Home", new { svm = Model })'" />

In my Controller :

public JsonResult GetNextAppointment(SuggestionViewModel svm)
{
     return Json(svm, JsonRequestBehavior.AllowGet);
    //this is just for testing
}

While debugging, I found out that my svm is null. I tried to replace it by a string parameter and hard coding the value in my view and this works. So, I don't know very much where is the problem.

Any idea guys?

EDIT : Code edited to use jQuery AJAX

My view's now like this :

@model AstellasSchedulerV2.Models.SuggestionViewModel

<div class="rightPanel">



        @using (Html.BeginForm("NewAppointment", "Home", FormMethod.Post, new { @id = "form_ValidateAppointment" }))
        {
            @Html.Hidden("stringParam","")
            <fieldset>
                <div>
                   Patch Anti-douleur Corps @Html.CheckBoxFor(s => s.PADC, new { @class = "checkbox", @id = "chbxPADC" })
                </div>
                <br />
                <div>
                   Patch Anti-douleur Pied @Html.CheckBoxFor(s => s.PADP, new { @class = "checkbox", @id = "chbxPADP" })
                </div>
                <br />
                <a href="#" id="ClickMe">Click me</a>

            </fieldset>
        }
    </div>

    <script type ="text/javascript">
        $(document).ready(function () {


            $("#ClickMe").click(function () {
                var o = new Object();
                o.PADC = $("#chbxPADC").val();
                o.PADP = $("#chbxPADP").val();

                jQuery.ajax({
                    type: "POST",
                    url: "@Url.Action("GetJson")",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(o),
                    success: function (data) { alert(data.PADC); },
                    failure: function (errMsg) { alert(errMsg); }
                });
            });
    </script>

2 Answers 2

4

Here goes the solution, Lets say you have your viewmodel this way -

public class SuggestionViewModel
{
    public bool PADC { get; set; }
    public bool PADP { get; set; }
}

Then you have a View in the following way. Here I used JQuery to make a POST request to GetJson Controller Action. I constructed a JavaScript Object and then serialized it to Json. Then finally passed the Json string to Controller Action.

<fieldset>
    <div>
        Patch Anti-douleur Corps @Html.CheckBoxFor(s => s.PADC, new { @class = "checkbox", @id = "chbxPADC" })
    </div>
    <br />
    <div>
        Patch Anti-douleur Pied @Html.CheckBoxFor(s => s.PADP, new { @class = "checkbox", @id = "chbxPADP" })
    </div>
    <br />

</fieldset>

This is the JQuery part -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {
        $("#ClickMe").click(function () {
            var chk = $('#chbxPADC').is(':checked');
            var chk1 = $('#chbxPADP').is(':checked');

            var o = new Object();
            o.PADP = chk1;
            o.PADC = chk;

            jQuery.ajax({
                type: "POST",
                url: "@Url.Action("GetJson")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(o),
                success: function (data) { alert(data.PADP); },
                failure: function (errMsg) { alert(errMsg); }
            });
        });
    });
</script>
<a href="#" id="ClickMe">Click me</a>

And when you click the button, it will hit following controller -

    public JsonResult GetJson(SuggestionViewModel svm)
    {
        return Json(svm, JsonRequestBehavior.AllowGet);
    }

And when you inspect the parameter using breakpoint, you will have parameters passed -

enter image description here

And as the response, you will have following output -

enter image description here

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

4 Comments

Thank you, it seems like it's a serious solution ! However, a little question : how can I pass my ViewModel to "o" ? Here you have hard-coded it, but how can I do it "dynamically"?
@Traffy You can get the values of input elements using JQuery, say for example you have an input text with id="txt1", then you can get its value in JQuery like $("#txt1").val(). Then you can get the object constructed in the code dynamically and send it to server.
Almost done I think. When I'm doing like you said (so with $("#txt1").val()), it's always true, even if it's not. Sorry but any idea about that? :/ When I checked the html source code, it clearly appears that it's false...
@Traffy, I updated my answer with exact your requirement :-). It it works, please dont forget to mark it as answer. And if possible an up vote :-).
1
  1. You can't post complex objects as parameter.
  2. If you want to get json result, you should call an ajax request.

You should post your model in an ajax request. (you can use jquery .ajax metod), because you cant get values from controller action metod if you use location.href

1 Comment

Thanks for your answer but I'm really new to all this stuff. Could you please take a look on the second part of the solution which was posted by Raphaël Althaus? I'd like to make it like this but unfortunately it does not work neither (I've posted an explanation).

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.