我想将html data- *属性绑定到我的模型中的单独属性。怎么做?
正如您在此处所见,我的按钮绑定到Operation属性,我想将data- *绑定到属性Data_RemoveAt。
public enum LinkListOperation
{
AddOne,
RemoveOne,
RemoveAll,
Submit,
RemoveAt
}
public class StepThree_Notification_TemplateEmailViewModel
{
public LinkListOperation Operation { get; set; }
[DisplayName("data-removeat")]
public int Data_RemoveAt { get; set; }
}
@using (var form = Html.BeginForm("AcceptTask", "Task", FormMethod.Post))
{
<div>Linki:</div>
for(int i = 0; i < Model.Links.Count; ++i)
{
<div>
@Html.TextBoxFor(f => f.Links[i], new { Name = string.Format("Model.Links[{0}]", i) })
<button value="RemoveAt" type="submit" name="Model.LinkOperation" data-removeat="@i">Remove</button>
</div>
}
<button value="AddOne" type="submit" name="Model.LinkOperation">MORE</button>
<button value="RemoveOne" type="submit" name="Model.LinkOperation">LESS</button>
<button value="RemoveAll" type="submit" name="Model.LinkOperation">REMOVE ALL</button>
<button value="Submit" type="submit" name="Model.Operation">OK</button>
}
答案 0 :(得分:0)
如果您不使用ajax,您可以做的是将提交按钮包装在表单标记内,并将要发送的值设置为表单字段。您可以使用隐藏字段。
for(int i = 0; i < Model.Links.Count; ++i)
{
<div>
@Html.TextBoxFor(f => f.Links[i],
new { Name = string.Format("Model.Links[{0}]", i) })
@using(Html.BeginForm("Remove","Home"))
{
<input type="hidden" name="Operation" value="@Model.Operation" />
<input type="hidden" name="RemoveIndex" value="@i" />
<button value="RemoveAt" type="submit" name="Model.Operation">Remove</button>
}
</div>
}
假设你的行动方法看起来像这样
public ActionResult Remove(string Operation,int RemoveIndex)
{
// to do : return something with the passed in values.
}
如果您已经拥有外部form
标记,则此方法并不理想,因为嵌套表单不是一个好主意。您可以考虑使用javascript-ajax代码来读取数据属性值并将其发送到服务器。
您不需要像我上面提到的那样添加表单标记。保持你的标记不行,除了,我们将在提交按钮中添加一个css类,稍后我们将使用它作为jQuery选择器。
<button value="RemoveAt" class='removeBtn' data-removeat="@i"
type="submit" name="Model.Operation">Remove</button>
添加此javscript以侦听按钮上的click事件并读取数据属性值,然后进行ajax post调用。假设您已将jQuery库加载到您的页面,
$(function(){
$(".removeBtn").click(function(e){
e.preventDefault();
var _this=$(this);
var removeIndex=_this.data("removeat");
var op=_this.attr("name");
var url = "@Url.Action("Remove","Home")";
url=url+"?Operation="+op+"&RemoveIndex="+removeIndex;
$.post(url,function(res){
//do something when a response comes back, may be update the UI/reload the page ?
//window.location.href=window.location.href;
});
});
});