How to use hidden field values from view to controller in asp.net mvc 3

前端 未结 3 1542
滥情空心
滥情空心 2021-02-08 03:38

I have to pass hidden filed values to controller action. So I have tried in the following way, but I am getting null values.

I have tried both methods i.e formcollection

相关标签:
3条回答
  • 2021-02-08 03:59

    It seems to me like you are trying to get multiple values into the POST controller. In that case, and by your exam, the value from the hidden input is enough. In that case, you can setup your controller as so:

    public ActionResult Index()
    {
        Hidden hd = new Hidden();
        return View(hd);
    }
    
    [HttpPost]
    public ActionResult Index(IEnumerable<string> hiddens)
    {
        foreach (var item in hiddens)
        {
            //do whatter with item
        }
        return View(new Hidden());
    }
    

    and as for your view, simple change it in order to bind to the same name "hiddens" as so:

    @using (Html.BeginForm(new { id = "postform" }))
    {
        <input type="hidden" value="7" name="hiddens" />
        <input type="hidden" value="2" name="hiddens" />
    
        <input type="submit" value="Match" />
    }
    

    Hope this serves what you are looking forward to.

    0 讨论(0)
  • 2021-02-08 03:59

    if your hidden value is static.Than try this

    View

    @using (Html.BeginForm(new { id = "postform" }))
    {
    
    
     @Html.HiddenFor(m=>m.hiddevalue)
        <input type="hidden" id="" value="7" name="hidden1" />
        <input type="hidden" id="" value="7"  name="hidden2"/>
    
        <input type="submit" value="Match"/>
    }
    

    Controller

    [HttpPost]
    public ActionResult MapIcon(Hidden hidden, string hidden1, string hidden2)
    {
        var hiddenvalue = hidden.hiddevalue;
        var hiddenvalue1 = hidden1;
        var hiddenvalue2 = hidden2;
        var value=hidden.hiddevalue;//null
        FormCollection col = new FormCollection();
        var value = col["hidden1"];
      //  string value = mycontroler.ControlName;
    
        return View(hidden);
    }
    

    Script

     $(document).ready(function () {
    
     $('#hiddevalue').val("Jaimin");
    
    });
    
    0 讨论(0)
  • 2021-02-08 04:09

    Try this, In Razor view:

    @using (Html.BeginForm(new { id = "postform" }))
    {
          @Html.HiddenFor(m=>m.hiddevalue)
         <input type="submit" value="Match"/>
    }
    
    0 讨论(0)
提交回复
热议问题