Skip to content Skip to sidebar Skip to footer

How To Pass Js Variable To @Model.MyModel (MVC4)

Here are my models public class AddressBook { public string UserId { get; set; } public IList
Addresses { get; set; } public AddressBook() {

Solution 1:

Wrap your elements in a spans with some class name. Wrap everything in the loop a div too. I am also removing the onclick method from the markup because we will do it in the unobtrusive way.

@for (int i = 0; i < Model.Addresses.Count; i++)
{
  <div class='entry'>
     <span class='spanAddress'> @Model.Addresses[i].Company </span>
     <span class='spanFName'> @Model.Addresses[i].FName </span>       
     <img src="/images/edit.gif" class='editLink' />
  </div>
}

Now in your javascript

$(function(){

  $(".editLink").click(function(e){

     e.preventDefault();
     var _this=$(this);
     var fname=_this.closest("div.entry").find(".spanFName").html();      
     var add=_this.closest("div.entry").find(".spanAddress").html();    

     $('#FName').val(fname);
     $('#Address').val(add);

  });  

});

Solution 2:

Well, this is client side code remember. So the best place to look is what is generated client side. This means commenting out your javascript event and looking at what is actually rendered to get an idea of what is going on.

When you do that, you will see that the helper autogenerates the names and ids based on your models names. Keep in mind that the name attribute on the inputs is what allows for model binding on post.

So, with all of that in consideration, I would assume it would be something along these lines:

function addressEdit(index) {
 $('#FName').val($("#Addresses_"+index+"__FName").val());
 //..etc
}

Post a Comment for "How To Pass Js Variable To @Model.MyModel (MVC4)"