Tony
Tony

Reputation: 12705

ASP.NET MVC Pass data from many <img> withe the same name to the controller

on my View, I have many <.img /> looking like that:

<img id="img1" name="myName" alt='aa' href='..' />
<img id="img2" name="myName" alt='bb' href='..' />
<img id="img3" name="myName" alt='cc' href='..' />

the question is, is it possible to get the alt attribute from the all <.img />'s with the same name and pass it to the controller as a e.g string[] ? The first thought was to use jQuery to join all that attributes as a one string and then pass it to the controller, but I'm wondering if there is some other approach

Upvotes: 0

Views: 188

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

You could use jquery to get all the alt values and send them to the server as an AJAX request:

var alts = $('img[name=myName]').map(function(i, item) {
    return $(item).attr('alt');
});

$.ajax({
    url: '/',
    data: { myName: alts.toArray() },
    traditional: true,
    success: function(result) {
        alert(result);            
    }
});

Upvotes: 1

ZaChickster
ZaChickster

Reputation: 429

There are only two ways get send data back to the server: the query-string and form POST values. If you want those alt tags sent back to the server you'll have to:

  • use JavaScript to take the alt information off the images.
  • for each image create a hidden input inside a form on the page.
  • each hidden input needs the same name with a value for each image.
  • submit the form via JavaScript.
  • MVC's binding will put each hidden inputs with the same name into a string[] you can use in your controller.

Upvotes: 1

&#199;ağdaş Tekin
&#199;ağdaş Tekin

Reputation: 16661

You're right. You'll have to use client-side scripting to send those values to the server.

There's no other way to capture them on the server-side.

Upvotes: 1

Related Questions