0

I learned some good things here here

What I want to know if it is possible to load these various JS model values, once the model is converted, from fields on the page without having to use

 model.ProductId = $("@txtProductId").val();

What I mean, and this may be a dumb question, is there a way to type in data directly into the JS field? Like the @Html.TextBoxFor to load controller model field for JS variable?

My product form looks somewhat like this:

 @model ProductModel
 <form id="productForm">
   <table>
     <tr>
       <td>@Html.TextBoxFor(o => o.BrandName, new {@id=txtBrandName})
      ///etc
Community
  • 1
  • 1
Dean.DePue
  • 1,013
  • 1
  • 21
  • 45
  • As I noted in the linked answer, you can just use `$('form').serialize();` but I suspect from your comments in that answer, your trying to dynamically add elements using partials and that the naming of your controls is wrong preventing the model from binding on postback. Have a look at the links in the 6th comment. –  Jan 26 '15 at 00:35
  • @StephenMuecke - let me understand - if the form is a partial and I give it an id, say, form1, then if I do var productModel = ('form1').serialize(); and then post productModel in an ajax call I will see all of the data as modified in the textboxes in the controller method? – Dean.DePue Jan 26 '15 at 07:13
  • Yes, that will work, but you need to ensure the the controls in the form are correctly bound- so if the partial is based on (say) `MyProductModel` then you need to post back to `ActionResult SomeAction(MyProductModel model)` –  Jan 26 '15 at 07:18
  • @StephenMuecke - awesome! I will give this a try a little later this morning when I get into work! – Dean.DePue Jan 26 '15 at 08:26
  • It could be as simple as `$.post('@Url.Action("yourActionName", "yourControllername")', $('form').serialize(), function (data) { // do something });` –  Jan 26 '15 at 08:56
  • @StephenMuecke - So I tried this with the product form with the id of ProductForm: $('ProductForm').serialize() and I get nothing, it's blank. Mind you, this JS function is in the order form not the product form but that shouldn't make a difference should it? – Dean.DePue Jan 26 '15 at 10:52
  • If the form has `id="ProductForm"` then it would need to be `$('#ProductForm').serialize();` (and the script should be in the main view, not the partial - which is what I think you mean) –  Jan 26 '15 at 10:56
  • @StephenMuecke - sorry, I just forgot to include the hash, it is like that and I am still getting nothing - var test = $("#ProductForm").serialize(); – Dean.DePue Jan 26 '15 at 10:59
  • @StephenMuecke - does it matter that I am using the using (Html.BeginForm("Method", "controller", ForMethod.Post, new { id="ProductForm"})) ? – Dean.DePue Jan 26 '15 at 11:10
  • No (although you would need to cancel the `.submit` event if applicable so it didn't do a standard submit as well as the ajax). What does `console.log(test);` output? –  Jan 26 '15 at 11:13
  • @StephenMuecke - well it doesn't matter either way I still get an empty string in the JS or the console. I am not submitting the partial view only calling a JS function in the main view. – Dean.DePue Jan 26 '15 at 11:24
  • If the `test` is empty then it suggests there are no controls in the form. Can you post the relevant code. –  Jan 26 '15 at 11:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69591/discussion-between-dean-depue-and-stephen-muecke). – Dean.DePue Jan 26 '15 at 11:33
  • @StephenMuecke - I was able to get it to work by loading a class in every field I need and then use $('.productForm').serializeArray(); and send that result with ajax to a method and it works just fine! – Dean.DePue Jan 26 '15 at 19:07
  • @StephenMuecke give me an answer that I can accept because you've helped me a lot in this... – Dean.DePue Jan 29 '15 at 07:59
  • In this case you should add your own answer with the code and explanation of how you solved it, and then accept it. –  Jan 29 '15 at 08:59

2 Answers2

0

One option you have is to use a javascript MVC framework like AngularJS, and then this will happen (more or less) automatically for you. You will probably want to create the text input using plain HTML instead of @Html.TextBoxFor.

For example, if you use AngularJS, your view would look like:

<input type="text" ng-model="model.ProductId" />

This creates a two-way data binding between your text box value and model.ProductId. What this means is that any time the user types a value into the text box, model.ProductId will automatically be set to the new value. Also any time you set model.ProductId in javascript, your text box will automatically update.

As a note, if you have any repeat sections in your view using @for loops, you will probably want to convert them to ng-repeat sections (for AngularJS at least).

AJ Richardson
  • 6,610
  • 1
  • 49
  • 59
0

I've found the best way to do this with a lot of help from Stephen Muecke. What I do is in the main page I have several DIVs:

 <div id="divPerson" style="display: none"></div>
 <div id="divProduct" style="display: none"></div>

In the JavaScript code I load each DIV with a partial view:

 function loadPerson() {
   $.ajax({
      type: 'POST',
      url: '@Url.Action("LoadPerson"),
      success: function(data) {
         $("#divPerson").html(data);
         $("#divPerson").show();
      }
   });

And the controller method:

 public ActionResult LoadPerson()
 {
     var model = new PersonModel();
     return PartialView("PersonPage", model);
 }

And in the PersonPage:

 $(document).ready(function() {
     $.validator.unobtrusice.parse();
 });

And each field in this page has a class of 'personForm'.

This is to read the validation tags again after the page has loaded so that clicking next is this in the main page:

 function goNext() {
   if (!$("#form1").valid()) {
       return false;
   }
   $.ajax({
      type: 'POST',
      url: '@Url.Action("AddPerson),
      data: $(".personForm").serializeArray(),
      success: function(data) {
          $("#divProduct").html(data);
          $("#divProduct").show();
          $("#divPerson").hide();
      }
   });

I do the same thing for the product page by setting a certain class and serializing those controls to send to the controller.

This, to me, is a good balance between using MVC and jQuery to make the page smooth, crisp, and clean, and enhance the user experience.

Dean.DePue
  • 1,013
  • 1
  • 21
  • 45