html.hidden在name属性更改时丢失值

时间:2014-10-29 14:17:52

标签: javascript jquery html asp.net-mvc

我在@html.editorfor视图中有一个@html.hiddenfor和一个my.cshtml元素,在按钮点击事件中,我更改了两个元素'命名属性,以便我可以将它们发布在单独的列表中。

editorfor元素的值应该是模型中的字符串,但hiddenfor元素的值应该是int。

问题是新列表以正确的编辑器值返回,但隐藏值总是返回" 0"即使它应该是别的东西。是否有不同的方法将int值发布回列表中?

顺便说一句,当我在不更改名称属性的情况下发布元素的值时,所有内容都会正确回发。

这是我用来更改名称属性的脚本:

//inside for loop where i is the iteration index
@Html.HiddenFor(m => m[i].EmployeeTimeSeriesDataID, new { htmlAttributes = new { @id = "tsdata_hidden_" + i } })

<script>
 $('somebutton').click(function() {
  var hiddenTsID = "#tsdata_hidden_" + aNumber; //number to match the i from the hidden for
  var nameOfHiddenToDeleteWithIndex = "deleteList[" + deleteIndex + "].EmployeeTimeSeriesDataID";
  //deleteindex starts at 0 and is incremented at the end of every button click, so the new list
  //can be correctly created starting with index[0]

  $(hiddenTsID).attr('name', nameOfHiddenToDeleteWithIndex);
 });
</script>

控制器动作:

public ActionResult TimeSeriesData(/*among other params*/EmployeeTimeSeriesData[] deleteList) {
 //working update functionality
 //working add functionality
 foreach (EmployeeTimeSeriesData tsData in deleteList)
  {
   EmployeeTimeSeriesData y = db.EmployeeTimeSeriesData.Find(tsData.EmployeeTimeSeriesDataID); 
   db.EmployeeTimeSeriesData.Remove(y);
  }
  db.SaveChanges();

}

2 个答案:

答案 0 :(得分:1)

显然html hiddenfor帮助器有问题。当我尝试检索值时,它返回空值,例如:

confirm($('tsdata_hidden_0').attr('value'))

这是打开一个带有空消息的确认框,'value'没有显示出来。同样的事情发生在我尝试同样的事情但有不同的属性时(而不是'value'我尝试'name''id'并且它们都是空白的。)

那么我所做的就是制作一个常规的html隐藏输入

<input type="hidden" id="someID" name="someName" value="someValue"/>

现在我做的时候

confirm($('someID').attr('value'))

确认框中显示"someValue"作为消息,不再为空白。再次感谢微软,让生活变得艰难

答案 1 :(得分:0)

列表装订夹可能有问题,请尝试:

var nameOfHiddenToDeleteWithIndex =
    "deleteList[" + deleteIndex + "].EmployeeTimeSeriesData.EmployeeTimeSeriesDataID";
相关问题