1

I'm implementing asp.net core 3.1. I have three radio buttons in my razor view and with the following code, I want to send the selected radio button value to Index action in controller in order to show its related data. My problem is after choosing a radio button and after that select the button. it send null value to the Index method.

Here my radio button code in razor

@model CSD.ChartObjects
 <form method="post">
        @foreach (var year in Model.Years)
        {
            <input type="radio" asp-for="Year" value="@year" />@year<br />
        }
        <input type="submit" asp-action="Index" />
    </form>

Here is my model object that is read in razor

    public class ChartObjects
    {
        public List<ChartModel> Percent { get; set; }
        public List<ChartModel> Time { get; set; }
        public List<ChartModel> Avg { get; set; }
        public List<ChartModel> Total { get; set; }

        [BindProperty]
        public string Year { get; set; }
        public string[] Years = new[] { "1398", "1399", "1400" };
    
}

And here is the body of my HomeController:

[HttpGet]
        public IActionResult Index()
        {
            return (BuildIndexModel("1399"));
        }

        [HttpPost]
        public IActionResult Index([FromForm] string currentYear)
        {
            return (BuildIndexModel(currentYear));
        }



        public IActionResult BuildIndexModel([FromForm] string currentYear)
        {
...
}
MinaMRM
  • 343
  • 4
  • 16

1 Answers1

2

The problem you're having is because of this:

[HttpPost]
public IActionResult Index([FromForm] string currentYear)

On your form, the value you want to bind is called Year, but in your POST action, you're specifying a parameter called currentYear. MVC doesn't know that you want to bind the value of Year to currentYear. Model binding is all based on the convention of property names on your model being the same as the data being sent from a form.

So all you need to do is change your POST method to this:

[HttpPost]
public IActionResult Index(string year)

Notice how I've also removed the [FromForm] attribute. You don't need to specify that here in order for it to bind properly. I'm guessing you added it while trying to figure out why it wasn't working. For the same reason, you also don't need the [BindProperty] attribute on your viewmodel - it's the name of the property that is important.

John H
  • 14,422
  • 4
  • 41
  • 74
  • Thank you for your reply.Now I have a problem to make one of those radiobutton to be checked by default. If I use the property check= checked, when I choose any other radio button than the default one, again the default radio button get checked. I appreciate if any one suggestss me a solution. – MinaMRM Sep 18 '20 at 07:15
  • @MinaMRM You should post that as a separate question, as it's a separate problem, but read [this answer](https://stackoverflow.com/a/54548610/729541) first and see if it helps. – John H Sep 18 '20 at 08:16