1

In my ASP.NET MVC page has a form for new records.

When the user saves a record I need to feed the value of a field of my "Model" within a Jquery function.

$('#checkBoxInsertPF').click(function(e){
    @Model.CNPJ = $(".....................").Val('')
});

How can I do this within a Jquery Block?

InsertNewRegister.cshtml

@Model.Cliente model

     @section scripts{
      <script type="text/jscript">
                 $('#checkBoxInsertPF').click(function(e) {
                   @Model.CNPJ = $(".....................").Val('')
     });
     }

Ram
  • 143,282
  • 16
  • 168
  • 197
user3154466
  • 23
  • 2
  • 5
  • Have you tried defining a Razor function in the @functions section of the page? I would try creating one that takes the parameter that you need to set on the model and sets that value to the model. See this link: http://stackoverflow.com/questions/5159877/how-do-i-define-a-method-in-razor – Joe Brunscheon Jan 02 '14 at 17:49

1 Answers1

0

You are going about this the wrong way. When your model is bound to your view, this is done on the server, before it gets to the client. As a result, javascript cannot change the values of the model that was sent. Meaning this:

$('#checkBoxInsertPF').click(function(e){
    //Cannot set a model value from client side in this manner
    @Model.CNPJ = $(".....................").Val('')
});

Will not work. However, you can set a hidden input for the model items that you need to update so that when the form is submitted, those values are bound back to the ViewModel in the action method.

View

@using(Html.BeginForm()){
    ...My Form Elements
    @Html.HiddenFor(x=>x.CNPJ);
}

Script Section

$('#checkBoxInsertPF').click(function(e){
    var newVal = $(".....................").Val('');
    $("#CNPJ").val(newVal);
});

This creates an element from your @Model.CNPJ field so that you can access it from jQuery and update the values. On POST, this value will be bound back to the model.

Tommy
  • 39,592
  • 10
  • 90
  • 121