Passing selected value from the radio buttons to the controller in MVC

前端 未结 6 1925
感动是毒
感动是毒 2020-12-10 04:58

I\'m trying to pass this selected radio button value from the razor view to the controller.... can someone please give me an idea how to do this?..................... My Vi

相关标签:
6条回答
  • 2020-12-10 05:09

    If you are giving same name for your radio buttons, then you can try the following code

    Controller

    [HttpPost]
    public ActionResult Index(string Answer)
    {
        return View();
    }
    

    View

    @using (Html.BeginForm("Index", "Demo"))
    {
           @Html.RadioButton("Answer", "A") <span>A</span> 
           @Html.RadioButton("Answer", "B") <span>B</span> 
    
        <input type="submit" value="Next" />
    }
    
    0 讨论(0)
  • 2020-12-10 05:09

    Use form collection

    [HttpPost]
        public ActionResult Index(FormCollection fc)
        {
    
          string answerA = fc["Answer1"];
          string answerB = fc["Answer2"];
          string answerC = fc["Answer3"];
          string answerD = fc["Answer4"];
          return View();
        }
    
    0 讨论(0)
  • 2020-12-10 05:09

    Add the following source code to View:

    @Html.RadioButtonFor(m => m.Role, "1" ) <span>A</span>
    @Html.RadioButtonFor(m => m.Role, "0" ) <span>B</span>
    @Html.HiddenFor(m=>m.Role)
    

    You can put the selected value to this HiddenField: @Html.HiddenFor(m=>m.Role) and send it to controller via [HttpPost] prototype.

    0 讨论(0)
  • 2020-12-10 05:12

    Either make a hidden field for every radio button or change you radio buttons like this

    @Html.RadioButtonFor("Answer1", new { @id = 1 })
    
    0 讨论(0)
  • 2020-12-10 05:14

    I saw this on another thread and it work like a champ.

    Razor view like this:

    @using (Html.BeginForm("test", "testcontroller"))
    {
      @Html.RadioButton("CashPayment", "1")<span>Yes</span>
      @Html.RadioButton("CashPayment", "0")<span>No</span>
    }
    

    And Controller like this:

    public ActionResult test(string CashPayment)
    {   
       //your code
    }
    
    0 讨论(0)
  • 2020-12-10 05:29

    Add property:

    public string SelectedAnswer { get; set; }
    

    Add in view:

    @Html.RadioButtonFor(m => m.SelectedAnswer, "Answer1")
    @Html.RadioButtonFor(m => m.SelectedAnswer, "Answer2")
    @Html.RadioButtonFor(m => m.SelectedAnswer, "Answer3")
    @Html.RadioButtonFor(m => m.SelectedAnswer, "Answer4")
    

    In controller it postback the value according to selected radio button... i.e. either Answer1, or Answer2, etc.

    0 讨论(0)
提交回复
热议问题