Unbreakable Unbreakable - 3 years ago 54
C# Question

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 am below code. is that the issue?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download