Search code examples
modelcontrollernullajax.beginform

IEnumerable Ajax.Beginform to Controller is null


I have a view contains a list of users that is passed through the model. What I want to do is have a button for each user using which passes the userId back to the controller so that I could store it. Similar to a Like/Unlike Button.

@model IEnumerable<FindaRoom.Models.FilterViewModel>
<h3>List of friends</h3>
<div class="row">
    @using (Ajax.BeginForm("Add", "User", null, new AjaxOptions
                    {
                        HttpMethod = "POST",
                        OnSuccess = "SuccessMessage",
                        OnFailure = "FailMessage",
                    }, FormMethod.Post))
    {
        foreach (var user in Model)
        {
            <div class="col-md-3">
                <div class="thumbnail">
                    <div>
                        @Html.EditorFor(modelitem => user.FbInfo.UserId)
                    </div>
                    <input type="submit" value="Match Me" />

                </div>
            </div>
        }
    }
</div>

When I post back the user.FbInfo.UserId I get a null value in my controller variable. I am not sure why I get a null variable but I think it might have to do something with my model?

I am just using an empty controller, and I am seeing the value always null.

    [HttpPost]
    public ActionResult Add(FilterViewModel text)
    {
        return new HttpUnauthorizedResult();
        //var user = db.Users.Find(text);
        //var curUser = UserManager.FindById(User.Identity.GetUserId());
        //curUser.Matches.Add(user);
        //db.SaveChanges();
    }

My model is as so.

public class FilterViewModel
{
    public FbInfo FbInfo { get; set; }
    public Questions Questions { get; set; }
}
public class FbInfo
    {
        public FbInfo()
        {
            this.friendsList = new List<friends>();
            this.mutualFriendsList = new List<mutualFriends>();
        }
        ...
        [Key]
        [ForeignKey("UserId")]
        public ApplicationUser User { get; set; }
        ...
    }
public class Questions
    {

            [Key]
            public int id { get; set; }
            [ForeignKey("UserId")]
            public ApplicationUser User { get; set; }
            public string UserId { get; set; }

    }

If anyone has a clue that would be helpful. I've been stuck on this for a bit and can't figure out why the text value in the controller is null.


Solution

  • You have wrong approach. Output of your code is single form with list of models and multiple submit button. I can suggest you my solution of similar problem.

    @model IEnumerable<FindaRoom.Models.FilterViewModel>
    <h3>List of friends</h3>
    
    <div class="row">
        @foreach (var user in Model)
        {
            <div class="col-md-3">
                <div class="thumbnail">
                    <button data-button="@user.FbInfo.UserId" class="btn btn-danger btn-match">Match Me</button>
                </div>
            </div>
        }
    </div>
    
    @section scripts {
        <script>
            $('.btn-match').click(function () {
                _self = this;
                var userId = $(_self).attr('data-button');
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Add", "User")',
                    data: {
                        userId: userId
                    },
                    success: function (response) {
                        SuccessMessage();
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        FailMessage();
                    }
                });
            })
        </script>
    }
    

    and your action will be

    [HttpPost]
    public ActionResult Add(string userId)
    {
        return new HttpUnauthorizedResult();
        //var user = db.Users.Find(userId);
        //var curUser = UserManager.FindById(User.Identity.GetUserId());
        //curUser.Matches.Add(user);
        //db.SaveChanges();
    }