使用“LabelFor”和“ValidationMessageFor”以及来自模型的 TextBoxFor 的唯一 ID

问题描述

我有一个 view,我在按钮点击事件(使用 ajax)上注入了一个 partialView。我的 partialView 包含一个 SelectList一个 TextBoxFor。现在,每次我注入这个部分时,我都会有一个 DDList一个 input 具有相同的 ID(还有 LabelForValidationmessageFor),这不是我想要的。我试图实现一种方法来构造该 id 动态(使其独一无二),但效果不佳。

viewmodel

public Ienumerable<Entity_DDList_Source> VM_DDList{get; set}//this gets populated in controller

[required]
[display(Name="Identity"]
public int id{get;set;}

[required]
[display(Name="Some details"]
public string details{get; set;}

PartialView - 经典方式

//this works well for only 1 generated model
@Html.LabelFor(m => m.id)
@Html.DropDownListFor(m => m.id,new SelectList(Model.VM_DDList),datavalueField: "tableId",datatextField: "tableText")
@Html.ValidationMessageFor(m=>m.id,"")

PartialView - 我尝试过的

// like this,validation message is not being displayed though my select border turns to red
@{var idComposer = "id_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute+ "_" + DateTime.Now.Second;}
@Html.Label(idComposer,"Label text here");
@Html.DropDownListFor(m => m.id,datatextField: "tableText",htmlAttributes: new {@id=idComposer })
@Html.ValidationMessage(idComposer,"") 

我怎样才能以一种经典的方式做到这一点,但具有唯一的 id?

解决方法

看起来我所需要的只是为 name 提供相同的唯一 ID:

@Html.DropDownListFor(m => m.id,new SelectList(Model.VM_DDList),datavalueField: "tableId",datatextField: "tableText",htmlAttributes: new {@id=idComposer,Name=idComposer })

1.请注意,在注入部分之后,您需要像这样解析表单验证

var $form = $("myForm");
$form.removeData('validator');
$form.removeData('unobtrusiveValdiation');
$.validator.unobtrusive.parse($form);

2.解析后,您还需要执行表单验证,否则验证器不会像应有的那样触发

$("myForm").valid()