简体   繁体   中英

Pass Value from View to Controller - MVC

i have a list of thumbnails for the user can select one of the image.

onclick on the thumbnail open a larger image into a form.

What im trying to do now is send the id of the image selected to my controller.

Note: im using MVC 4.

how can i do that?

someone can help with this pls?

Thanks in advance:

Here is my code:

 @foreach (var p in ViewBag.Images)
    {           
     <li>
       <a href="~/Files/@p.Name" onclick="swap(this); return false;">
          <img src="~/Files/@p.Name"/>
       </a>
     </li>
}

when selected is going this img tag in my form:

<img id="main" src="" >

using this javascript for this event:

function swap(image) {
        document.getElementById("main").src = image.href;
    }

what i have to do now?

i trying with <input type="hidden" name="Img_Id" value="Viewbag.??????"/> to pass this value to my controller??

First, some terminology help: You can't pass a value from the view to the controller action, the view is rendered after the controller action completes.

What you want to do is pass data from the client (web browser) to a controller action, using form fields.

In your javascript swap method, you could set the value of the Img_Id field to be the value for the selected image. When the form is submitted, the Img_Id will be posted as form data, and can be accepted as a parameter in the action.

You can use JQuery (or something else) to perform the client side actions.

Here's an example (not tested though!):

First add the ID as a data attribute on the element:

<a href="~/Files/@p.Name" data-id="@p.ID" onclick="swap(this); return false;">

Then some javascript to save that to form (using jquery here):

function swap(image) {
    document.getElementById("main").src = image.href;
    $("input[name='Img_Id']").val($(image).data("id"));
}

To pass a value back to your controller, you either need to submit a form, or else make an AJAX request to your controller.

In the first case, you'd need to update the value of your hidden field with javascript, and then either wait for the user to submit the form, or trigger a submit through javascript depending on what your needs are.

If you want to do an ajax request, it would be more or less the same thing, but you don't need a hidden field to store the value.

You could use jQuery in your swap function. See here for the official documentation.

If you chose to use this approach, and assuming you place your JavaScript in a separate file, then make sure you get the path for the action and controller and pass that in too.

var url = @Url.Action("Index","Home");

Therefore you may call: onclick="swap(this.id, url)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM