简体   繁体   中英

How to Pass ID to MVC ActionResult using jQuery?

How do I pass the id retrieved from radiobuttonfor to MainPage controller - Edit1 actionresult in View. Anyhelp will be appreciated! Thanks!

//View in for loop to display contents and radiobutton

@foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.SurveyTitle)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.DateCreated)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.DateClosing)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.User)
                    </td>
                    <td>
                        @Html.RadioButtonFor(modelItem => item.SurveyId, new {id = item.SurveyId})
                    </td>
                </tr>
            }


          <button type="submit" class="btn btn-primary" id="edit">Edit</button>

//Script for button to detect which radiobutton id is selected and submit

<script>            
        $('#edit').click(function () {

            var id = $('input[type=radio]:checked').val();
            alert(id);


        });

         </script>

//Controller to get the id and take surveyid out

[HttpPost]
             public ActionResult Edit1(int id=0)
            {
                survey survey = db.surveys.Single(s => s.SurveyId == id);
                if (survey == null)
                {
                    return HttpNotFound();
                }
                return View(survey);
            }

try this:

http://api.jquery.com/jQuery.post/

Or place your id to some hidden text field and trigger click on submit button (if you have web-form on a page)

It looks like you are trying to change the window's location when the user clicks edit based upon a particular id set by a radio button list.

I think you'd be able to do something like this:

$('#edit').click(function () {

    var id = $('input[type=radio]:checked').val();
    window.location.href='/MainPage/Edit1/'+id;
    //window.location.href='/MainPage/Edit1/?id='+id; //if {controller}/{action}/{id} isn't setup in the routing class.

});

Where is this submit button you speak of? Is it #edit ? You need to let it POST the form if you want to reach a POST action. Also, it won't bind to int id in your action unless you change the radio to something like @Html.RadioButton("id", item.SurveyId)

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