2

As you can see I have a for loop with Multiple ID and I want get the value of IDs and pass them to my controller, how can I achieve this ?

<form id="UserEdit">
         @for (int i = 0; i < Model.Rights.Count; i++)
          { 
            @Html.HiddenFor(m => m.Rights[i].ID)
          }

       <input id="BtnEditUserJS" onclick="PostFormUserEdit();" type="submit" value="Edit">
 </form>

Generated HTML:

<input id="Rights_0__ID" name="Rights[0].ID" type="hidden" value="31">

<input id="Rights_1__ID" name="Rights[1].ID" type="hidden" value="32">

JavaScript:

function PostFormUserEdit() {  
    $.ajax({
        type: 'POST',
        url: '@Url.Action("EditUser")',
        dataType: 'json',
        data: ,
        success: function (run) {
            console.log('Ok');
            },
        error: function () {
          console.log('something went wrong - debug it!');
            }
        });
}

Controller:

    [HttpPost]
    public JsonResult EditUser(int[] RightId)
    {
        var rights = db.Rights.Where(b => RightId.Contains(b.Id)).ToList();

       //do something with rights
    }
5
  • Serializing the form should do that... Commented Aug 29, 2019 at 13:36
  • @mplungjan what if i want pass as parameter ?! Commented Aug 29, 2019 at 13:38
  • 2
    You need to NOT use onclick but instead $(function() $("#UserEdit").on("submit",function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '@Url.Action("EditUser")', dataType: 'json', data: $(this).serialize() , ... Commented Aug 29, 2019 at 13:42
  • @mplungjan when i use serialize my RightId becomes to null in controller and as you see my action singature wating/accept to get RightId as parameter. Commented Aug 29, 2019 at 14:06
  • If the values never change, you could just convert your list to JSON in the code behind and put the resulting string in the view inside a <script> tag. That way, your data will already be ready to be sent. Also, if you have a submit with an onclick, it will try to do both at the same time. Commented Aug 29, 2019 at 14:10

1 Answer 1

1

You can achieve it this way :

function PostFormUserEdit() 
{  
    var arr = [];
    $("#UserEdit input[type='hidden']").each(function (index, obj) {
        arr.push(obj.val());
    });

    $.ajax({
        type: 'POST',
        url: '@Url.Action("EditUser")',
        dataType: 'json',
        data: arr ,   // or you can try data: JSON.stringify(arr)
        success: function (run) {
            console.log('Ok');
            },
        error: function () {
          console.log('something went wrong - debug it!');
            }
        });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.