ASP.NET MVC从单个元素绑定到多个模型属性
本文关键字:模型 属性 绑定 元素 NET MVC 单个 ASP | 更新日期: 2023-09-27 18:28:35
我想将html data-*属性绑定到模型中的单独属性。如何做到这一点?
正如您在这里看到的,我的按钮绑定到Operation属性,我想将data-*绑定到属性data_MoveAt。
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>
}
如果您不使用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来监听按钮上的点击事件,读取数据属性值,然后进行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;
});
});
});