user1815436
user1815436

Reputation: 31

asp net MVC3 submit List of object is null when post back

I use asp net MVC 3 one of my project.I use partial view for my coding. I want to list all customers in a list and submit their information as a list. When I try to submit my list in post back, it sends my list is null. You can find my code as in the below:

My controller method is:

[HttpPost]
    public ActionResult ConfirmUsers(ICollection<Career.DomainModel.UserApprovalDto> collection)
    {
        string bas = "";
        //if (collection != null)

        if (ModelState.IsValid)
        {
            bas = "bas";
        }

        return RedirectToAction("Index");
    }

My partial view is:

@model List<Career.DomainModel.UserApprovalDto>
@using (Html.BeginForm("ConfirmUsers", "ManageUsers", new { area = "" }, FormMethod.Post))
{
    <table>
        <tr>
            <th>
                Name
            </th>
            <th>
                Is Reported
            </th>
        </tr>
        @for (int i = 0; i < Model.Count(); i++)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => Model[i].FirstName)
                </td>
                <td>
                    @Html.CheckBox("IsReported", Model[i].IsReported.HasValue ? Model[i].IsReported.Value : false)
                    @*@Html.CheckBoxFor(modelItem => Model[i].IsReported.Value);*@ @*    @if (Model[i].IsReported != null)
                    {
                        @Html.CheckBoxFor(modelItem => Model[i].IsReported.Value);
                    }
                    else
                    {
                        @Html.CheckBoxFor(modelItem => Model[i].IsReported.Value);
                    }*@
                </td>
                <td>
                </td>
            </tr>
        }
    </table>
    <div>
        <input name="submitUsers" type="submit" value="Save" />
    </div>
}

Thanks in advance.

Kerem

Upvotes: 3

Views: 7321

Answers (5)

pureevill
pureevill

Reputation: 99

i run into same problem last week.

I realize that checkbox has three value(true/false/null) when i get it from database because i let the checkbox value nullable when i desingned database. i redesinged db and the problem was solved.

you didnt post models so i dont realy sure if this is the case. just look at the model, if it's writing Nullable above your Ischeck property, go to database and redesign. remember isCheck, isSelected properties have to have just two values(true/false).

Upvotes: 0

neha beke
neha beke

Reputation: 1

@Html.CheckBox("[" + i + "]." + "IsReported", Model[i].IsReported.Value); worked perfectly for me.

Make sure your post method contains parameter for the list. e.g public ActionResult Index(ConfigViewModel model, List configurationList)

Here in my case I have one view model (model) which contains list object. If you specify view model in your post method as it is then you will get null value for the list (here model object is null). But if you add specific list parameter (configurationList) in the action then you can get all of the list values in the controller.

Upvotes: 0

Laz
Laz

Reputation: 43

I'm a little late to the party, but it is easy enough to just refer to the list if you embed it in the model--

@Html.CheckBoxFor(modelItem => Model.List[i].Selected)

That will post back for each item in the iterator.

Upvotes: 0

Cuong Nguyen
Cuong Nguyen

Reputation: 331

With the code you wrote, MVC model binder mechanism does not know how to map those inputs into List of object.

Do this little trick instead:

@Html.CheckBox("[" + i + "]." + "IsReported", Model[i].IsReported.Value);

This will result the name of input field as [0].IsReported for the first item in the list, [1].IsReported for next item.

That should work.

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Upvotes: 0

Shyju
Shyju

Reputation: 218722

I would use Editor template to handle this. Have your View Model like this to represent the CheckBox item.

public class ReportedUserViewModel 
{
  public string FirstName { set;get;}
  public int Id { set;get;}
  public bool IsSelected { set;get;}
}

Now in yout main view model, add a property which is a collection of the above class

public class ConfirmUserViewModel
{      
  public List<ReportedUserViewModel> ReportedUsers{ get; set; }      
  //Other Properties also here

  public ConfirmUserViewModel()
  {
    ReportedUsers=new List<ReportedUserViewModel>();       
  }    
}

Now in your GET Action, you will fill the values of the ViewModel and sent it to the view.

public ActionResult ConfirmUser()
{
    var vm = new ConfirmUserViewModel();

    //The below code is hardcoded for demo. you mat replace with DB data.
    vm.ReportedUsers.Add(new ReportedUserViewModel { Name = "Test1" , Id=1});
    vm.ReportedUsers.Add(new ReportedUserViewModel { Name = "Test2", Id=2 });

    return View(vm);
}

Now Let's create an EditorTemplate. Go to Views/YourControllerName and Crete a Folder called EditorTemplate and Create a new View there with the same name as of the Property Name(ReportedUsers.cshtml)

Add this code to the newly created editor template.

@model ReportedUserViewModel 
<p>
  <b>@Model.FirstName </b>   :
  @Html.CheckBoxFor(x => x.IsSelected) <br />
  @Html.HiddenFor(x=>x.Id)
</p>

Now in your Main View, Call your Editor template using the EditorFor Html Helper method.

@model ConfirmUserViewModel
@using (Html.BeginForm())
{
    <div>  
      @Html.EditorFor(m=>m.ReportedUsers)         
    </div>    
    <input type="submit" value="Submit" />
}

Now when You Post the Form, Your Model will have the ReportedUsers Collection where the Selected Check boxes will be having a True value for the IsSelected Property.

[HttpPost]
public ActionResult AddAlert(ConfirmUserViewModel model)
{
   if(ModelState.IsValid)
   {
      //Check for model.ReportedUsers collection and Each items
      //  IsSelected property value.
      //Save and Redirect(PRG pattern)
   }
   return View(model);
}

Upvotes: 2

Related Questions