简体   繁体   English

MVC EditorFor日期不会更新foreach循环中的sub属性

[英]MVC EditorFor date doesn't update the sub property in foreach loop

I'm passing the model to the View and then I want to change user.BannEndDate in the view and send it back to the controller. 我将模型传递给View,然后要在视图中更改user.BannEndDate并将其发送回控制器。 No matter what I will do with user.BannEndDate ActionLink always pass the value which was set by arrived model. 无论我将如何处理user.BannEndDate,ActionLink始终传递到达模型设置的值。 Can anyone help me with that ? 有人可以帮我吗?

[Model] [模型]

[DataType(DataType.Date)]
public DateTime? BannEndDate { get; set; }

[View] [视图]

@foreach (var user in Model.Users)
{
    @Html.ActionLink("Bann", "BannUser", "Account", new { userId = user.Id, bann = true, bannEndDate = user.BannEndDate} , null)
    @Html.EditorFor(u => user.BannEndDate)
}

[Controller] [控制器]

public ActionResult BannUser(string userId, bool bann, DateTime? bannEndDate){}

As Mike McCaughan already stated, the values for @Html.ActionLink are static, since they're written when you call the page. 正如Mike McCaughan所述, @Html.ActionLink的值是静态的,因为它们是在您调用页面时写入的。

What you could do, is give your ActionLink and EditorFor a specific ID. 您可以做的是为您的ActionLinkEditorFor一个特定的ID。

@Html.ActionLink("Bann", "BannUser", "Account", new { userId = user.Id, bann = true, bannEndDate = user.EndDate }, new { @id = "TargetLink_" + user.Id })
@Html.EditorFor(m => user.BannEndDate, null, "BannEndDate_" + user.Id)

After that you can listen to changes on those controls via jQuery and change your ActionLink ( userId = 3 will result in BannEndDate_3 and TargetLink_3 ): 之后,您可以通过jQuery监听那些控件上的更改并更改您的ActionLink( userId = 3将导致BannEndDate_3TargetLink_3 ):

$('input[id*="BannEndDate_"]').change((e) => {
    var userId = e.target.id.substr(e.target.id.indexOf("_") + 1);
    var link = $("#TargetLink_" + userId).attr('href');
    $("#TargetLink_" + userId).attr('href', link.replace(/(bannEndDate=.*$)/g, 'bannEndDate=' + encodeURIComponent($("#" + e.target.id).val())));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM