11

我必须将隐藏的字段值传递给控制器​​操作。所以我尝试了以下方式,但我得到了空值。

我已经尝试了这两种方法,即 formcollection 和 viewmodel 概念

控制器

public ActionResult MapIcon()
{
    Hidden hd = new Hidden();
    return View(hd);
}

[HttpPost]
public ActionResult MapIcon(Hidden hidden)
{
    var value=hidden.hiddevalue;//null
    FormCollection col = new FormCollection();
    var value = col["hidden1"];
  //  string value = mycontroler.ControlName;

    return View(hidden);
}

看法

@model SVGImageUpload.Models.Hidden
Razor view:@using (Html.BeginForm(new { id = "postform" }))
{
    <input type="hidden" id="" value="7" name="hidden1" />
    <input type="hidden" id="" value="7"  name="hidden2"/>

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

视图模型

public class Hidden
{
  public string hiddevalue { get; set; }
}
4

3 回答 3

9

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.

于 2013-08-08T15:25:59.137 回答
9

试试这个,在 Razor 视图中:

@using (Html.BeginForm(new { id = "postform" }))
{
      @Html.HiddenFor(m=>m.hiddevalue)
     <input type="submit" value="Match"/>
}
于 2013-08-08T07:53:51.250 回答
3

如果您的隐藏值是静态的。那就试试这个

看法

@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"/>
}

控制器

[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);
}

脚本

 $(document).ready(function () {

 $('#hiddevalue').val("Jaimin");

});
于 2013-08-08T08:29:02.123 回答