CatfishAlpha45
CatfishAlpha45

Reputation: 77

MVC 5 Razor Variable Change on HTML Button click

NET and MVC, I'm trying to work on a beginner project and I'm kinda of stuck.

I have data model that contains multiple picture paths in it and I'm wondering how could I change which the picture I want to display in my view on button click. Example: show picture 1, click a HTML button, and change to show picture 2.

This is what I got so far? How am I supposed to change the picID variable? Could someone explain please?

    <tr>
       <td><button type="button">Click this to change the picID variable</button></td>
       <td>@Html.DisplayFor(model => model.Picture.ElementAt(picID).picturePath)</td>
    </tr>

Upvotes: 1

Views: 3680

Answers (3)

Alex
Alex

Reputation: 546

What you'll want to do is have the button invoke an action method that changes picID and returns your view. Something like /controller/changepic/1. Changepic will update picID to 2 and then return the same view and model.

The tricky part here is that button is generally used to submit forms. So you either have to add an event handler to manually set the action link or use an anchor element (@Html.ActionLink) styled like a button. You can use bootstrap to do that kind of styling.

I made a lot of assumptions, but hope this helps.

Upvotes: 3

ProtoCUS
ProtoCUS

Reputation: 49

I have a similar situation, I wanted to change an image depending on the combo value, so I use JQuery

in the cshtml I put a that contains the images I have:

<img class="imgf"> ...
<img class="imgp"> ...
<img class="imgb"> ...

The Jquery code on Combo Change:

var model = $("#ComboValue").val();
var pathgimgf = "/Images/" + model + "/imgf.png";
var pathimga = "/Images/" + model + "/imga.png";
var pathimgb = "/Images/" + model + "/imgb.png";


$(".imgf").attr("src", pathgimgf);
$(".imgp").attr("src", pathimga);
$(".imgb").attr("src", pathimgb);

I hope this can help you.

Upvotes: 1

Andre Calil
Andre Calil

Reputation: 7692

There are many ways. Check this out:

<img id="theImage" src="" />
<ul>
    @foreach (var i in Model.Picture)
    { 
        <li><a href="#" data-image="@i.picturePath" class="change-image">@i.picturePath</a></li>
    }
</ul>
<script type="text/javascript">
    $(function () {
        //Click event for the image links
        $('.change-image').click(function (e) {
            e.preventDefault();
            e.stopPropagation();

            $('#theImage').attr('src', $(this).data('image'));
        });

        //Display the first link
        $('#theImage').attr('src', $('ul li:first-child a.change-image').data('image'));
    });
</script>

Notice that I'm using jQuery.

Please let me know if this helps.

Upvotes: 1

Related Questions