Pass values of checkBox to controller action in asp.net mvc4

后端 未结 12 1453
长发绾君心
长发绾君心 2020-12-14 00:31

I want to test if the checkbox is checked or not from my action method, what i need is to pass checkbox value from view to controller.

This is my view:



        
相关标签:
12条回答
  • 2020-12-14 01:04

    For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this

    @Html.CheckBox("checkResp")
    

    to create a checkbox that would play nice with the controller.

    0 讨论(0)
  • 2020-12-14 01:04
     public ActionResult Save(Director director)
            {
              // IsActive my model property same name give in cshtml
    //IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive" 
                if(ModelState.IsValid)
                {
                    DirectorVM ODirectorVM = new DirectorVM();
                    ODirectorVM.SaveData(director);
                    return RedirectToAction("Display");
                }
                return RedirectToAction("Add");
            }
    
    0 讨论(0)
  • 2020-12-14 01:07
    <form action="Save" method="post">
     IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive"  />
    
     </form>
    
     public ActionResult Save(Director director)
            {
                       // IsValid is my Director prop same name give    
                if(ModelState.IsValid)
                {
                    DirectorVM ODirectorVM = new DirectorVM();
                    ODirectorVM.SaveData(director);
                    return RedirectToAction("Display");
                }
                return RedirectToAction("Add");
            }
    
    0 讨论(0)
  • 2020-12-14 01:13

    For the MVC Controller method, use a nullable boolean type:

    public ActionResult Index( string responsables, bool? checkResp) { etc. }

    Then if the check box is checked, checkResp will be true. If not, it will be null.

    0 讨论(0)
  • 2020-12-14 01:14

    try using form collection

    <input id="responsable" value="True" name="checkResp" type="checkbox" /> 
    
    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
         if(!string.IsNullOrEmpty(collection["checkResp"])
         {
            string checkResp=collection["checkResp"];
            bool checkRespB=Convert.ToBoolean(checkResp);
         }
    
    }
    
    0 讨论(0)
  • 2020-12-14 01:15

    set value in check box like this :

    <input id="responsable" name="checkResp" value="true" type="checkbox" />
    

    change checkResp to nullable property in Your model like this :

    public Nullable<bool> checkResp{ get; set; }
    

    use ? before checkResp like :

    public ActionResult Index( string responsables, bool ? checkResp)
    {
     ......
    }
    
    0 讨论(0)
提交回复
热议问题