2

我有一个项目列表的视图。每个项目都有一个文本框和一个按钮。获取在控制器操作中单击的按钮的项目 ID 的最佳方法是什么?我需要控制器操作中关联文本框中的值,所以我认为我不能使用操作链接。

4

3 回答 3

2

有很多方法可以做到这一点。有些使用 javascript,有些则不使用。我个人更喜欢不将 javascript 用于基本功能,除非您的设计本身是基于 javascript 的(例如使用 ajax)

例如,您可以将每个项目包装在它自己的表单中,并使用不同的提交值。请注意不要嵌套表单,因为那不是有效的 HTML。

例如:

@using(Html.BeginForm("MyAction", "MyController", new { id=1 })) {
    <input type="submit"/>
    @Html.TextBox("TheValue", "One")
}

@using(Html.BeginForm("MyAction", "MyController", new { id=2 })) {
    <input type="submit"/>
    @Html.TextBox("TheValue", "Two")
}

public ActionResult MyAction(int? id, string TheValue) {
     // if they click the first one, id is 1, TheValue = "One"
     // if they click the second one, id is 2, TheValue = "Two"
}
于 2013-10-06T22:03:53.853 回答
1

这个答案是使用 jquery - 如果您不知道如何将 jQuery 添加到您的视图中,或者只是不想使用它,请告诉我,我可以重新编写答案

我会做这样的事情

<li>
   <input type="text" id="1" name="1" class="whatever" />
   <input type="button" value="CliCk mE" class="myButton" />
</li>
<li>
   <input type="text" id="2" name="2" class="whatever" />
   <input type="button" value="CliCk mE" class="myButton" />
</li>
<input type="hidden" id="myHiddenText" name="myHiddenText" />

然后添加这个jQuery:

<script>
$(function(){
   $('.myButton').click(function(){
       // this is how to get the closest textbox
       // you didn't show your html , maybe .prev() or .next()
       var textValue = $(this).closest("input[type='text']").val();

       // this sets your hidden field with the value from desired textbox
       $('#myHiddenText').val(textValue);
    });
});
</script>

现在,当您将此表单提交到服务器时,您可以在服务器上使用 myHiddenText

    public ActionResult Index(string myHiddenText = "")
    {
        // hidden fields in the HTML form automatically get passed to server on submit
        return View();
    }
于 2013-10-06T08:36:07.450 回答
0

最好的选择是使用 jquery,但如果你只想使用 c#,我建议如下:

我想你正在使用某种重复语句(for 或 foreach)来生成你的文本框,所以我要做的是在 foreach 中创建一个表单,这个新表单将包含你的文本框,而你将传递文本框 id 的 foreach 项目表单提交。

像这样的伪代码:

foreach(item in array){
  <form action="address/"@item.Id>
    <input type="text" value=""/>
    <input type="submit" value="submit textbox"/>
  </>
}
于 2013-10-06T21:39:16.643 回答