1

I can't pass complex class from Radio Button to Controller. Is it possible, how I am doing it ? I just want to send a object using radio button. The problem is, I receive error null reference.

public class Model1
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<ComplexClass> example { get; set; }
    public List<string> SimpleCollection { get; set; }
}

public class ComplexClass
{
    public int numerek { get; set; }
    public string slowo { get; set; }
}

Here is a view

@using (Html.BeginForm("GetInfosFromView", "Home", FormMethod.Post)){

//@helper(Model)
@Complex(Model)

<input type="submit" value="Submit" />}


@helper helper(WebApplication1.Models.Model1 modelx){
<ul>
    @foreach (var item in modelx.SimpleCollection)
    {
        <li>@item @Html.RadioButtonFor(m => m.SimpleCollection[0], item)</li>
    }
</ul>}


@helper Complex(WebApplication1.Models.Model1 collection){
<ul>
    @foreach (var item in collection.example)
    {
        <li> @item.Word || @item.Number @Html.RadioButtonFor(m => m.example[0], item)</li>
    }
</ul>}

namespace WebApplication1.Controllers{ public class HomeController : Controller {

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Form()
    {
        Model1 model1 = new Model1();
        model1.SimpleCollection = new List<string>(){"raz", "dwa", "trzy"};
        model1.example = new List<ComplexClass>() {new ComplexClass(){ Number=500, Word="piecset"},
                                                    new ComplexClass(){ Number=1000, Word="tysiąc"},
                                                    new ComplexClass(){ Number=100, Word="sto"}
        };

        return View("Form", model1);
    }

    //[HttpPost]
    //public ActionResult GetInfosFromView(Model1 model2)
    //{

    //    var model = "";
    //    model = model2.SimpleCollection[0];

    //    ViewBag.Info = model;

    //    return View("Index");
    //}

    [HttpPost]
    public ActionResult GetInfosFromView(Model1 model2)
    {

        var model = "";
        model = model2.example[0].Number.ToString();

        ViewBag.Info = model;

        return View("Index");
    }
}

}

1
  • No, you cannot bind radio button (or any any other form control) to a complex object. A radio button only posts back a single value. And inspect the html your generating for @Html.RadioButtonFor(m => m.example[0], item) - in particular the value attribute to understand why this will never work.
    – user3559349
    Jun 27, 2016 at 2:02

1 Answer 1

1

Yes you can. What you want to do is the following (Note the addition of a new property in your data class; the IsSelected property):

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Custor.Controllers.radiobuttontest
{
    public class radiobuttontestController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            // instantiating the POCO class
            Model1 TestData = new Model1();
            // Populating the instantiated class
            TestData.ID = 1;
            TestData.Name = "IncomingName";
            TestData.SimpleCollection = new List<string>() { "raz", "dwa", "trzy" };
            TestData.Example = new List<ComplexClass>() {
                new ComplexClass(){ Number=500, Word="piecset", IsSelected=true},
                new ComplexClass(){ Number=1000, Word="tysiąc", IsSelected=false},
                new ComplexClass(){ Number=100, Word="sto", IsSelected=false}
            };
            return View("Index",TestData);
        }

        // You can experiment with the binding here, to leave out or include as many fields as you like from the data model bound to the ActionResult
        [HttpPost]
        public ActionResult Index([Bind(Include = "ID,Name,Example,SimpleCollection")] Model1 IncomingSelection)
        {
            string selectedname = IncomingSelection.Name;  // put a breakpoint on this line, to study the Debug > Windows > Locals output, and observe that the values are successfully posted.
            return View("Index", IncomingSelection); // post the incoming data right back to the view again
        }
    }

    public class Model1
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<ComplexClass> Example { get; set; }
        public List<string> SimpleCollection { get; set; }
    }
    public class ComplexClass
    {
        public int Number { get; set; }
        public string Word { get; set; }
        public Nullable<bool> IsSelected { get; set; }
    }
}

.. and your view like this

@* This is the your POCO class, in this case is placed inside the controller itself; hence this namespace.*@
@model  Custor.Controllers.radiobuttontest.Model1

@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>The test controller view</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        for (int x = 0; x < Model.Example.Count; x++)
        {
            <label>
                <input name="Example[0].IsSelected" id="Example[@x].IsSelected" type="radio" value="true">
                @Model.Example[x].Word
            </label>
            @Html.HiddenFor(m => m.Example[x].Word)
            @Html.HiddenFor(m => m.Example[x].Number)
        }
        <p><input type="submit" value="Post the selection" class="btn btn-default" /></p>
    }
</body>
</html>

If you observe the incoming data from the view in the back end (the controller's Post actionResult), you will see that all the radios are coming in, but only chosen one has its IsSelected property set to true.

And if you change the radiobutton to this:

@Html.RadioButtonFor(m => m.Example[x].IsSelected, true)

.. all the radios will respect the initial value set in the controller befor rendered, but they will not function completely correctly when selecting between them. (could be solved with a tiny javascript though). Another good thing with this is that the IsSelected property is populated in all rows of the list; not just the selected one (true) but the ones not selected will bear the value false (set initially in the controller).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.