Unbreakable
Unbreakable

Reputation: 8132

How to set a Model property inside javascript and be able to receive it in POST method

I have a button when that button is clicked I want to set a model property to true and be able to receive it in the back end. Code is a bit messed up but bear with me please as I have taken alot of code out of it.

@model FullConfigurationMV
 @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "MyForm" }))
    {
        @Html.HiddenFor(model => model.IsTemplate)

        // Code removed for brevity 
        <button id="DraftName">Click me</button>

    }
    <script>
    $( document ).ready(function() {
        debugger;
        $("#DraftName").click(function()
        {
            @Model.IsTemplate = true; // I AM SETTING THE VALUE AS TRUE
                SaveStyles();
        });
    });
</script>

<script>
function SaveStyles() {
    var data = $('#MyForm').serialize();
    var URL = "SOME URL"
    $.ajax({
        url: URL,
        type: 'POST',
        data: data,

        success: function (result) {

        },
        error: function (error) {
        }
    });
}
</script>

POST ACTION

 public JsonResult SaveStyles(FullConfigurationMV data)
        {
                 // data.IsTemplate is coming out to be false
                // Rest of the UI control data is coming back properly
        }

EDIT Since I have below code. is that the issue?

var data = $('#MyForm').serialize();

Upvotes: 0

Views: 1045

Answers (2)

CodeNotFound
CodeNotFound

Reputation: 23250

Razor view are generated in server side. So when you browser get the HTML there is no razor code in it so the following code will not work:

$("#DraftName").click(function()
{
    @Model.IsTemplate = true; // <-- this will not work and will not exist in client side
    SaveStyles();
});

You should set the hidden field you just put in your form @Html.HiddenFor(model => model.IsTemplate) which generate <input type='hidden' /> and just update your javascript code by doing this:

$("#DraftName").click(function()
{
    $("#MyForm input[type='hidden']").val("true"); //  <- Replace your Razor code with this.
    SaveStyles();
});

Upvotes: 2

Fran
Fran

Reputation: 6530

Think about this problem a little differently.

All the view does is render html. Since you have a form in html, all your javascript has to do is to set the form element's value to true.

You should be able to use the jQuery selector like

$('input:hidden[name=IsTemplate]').val(true);

And your form serialize should pick it up.

Upvotes: 3

Related Questions