1

I have a view model for editing a users settings. One of its properties is defined as

<Display(Name:="View_User_Profile_Language", ResourceType:=GetType(Resources.UIText))>
Public Property Language As String

And in the view, I use it like this:

<%: Html.LabelFor(Function(m) m.UserInfoForm.Language) %>
<%: Html.DropDownListFor(Function(m) m.UserInfoForm.Language,
                 languages.Select(Function(lang) New SelectListItem With {
                     .Text = New Globalization.CultureInfo(lang).NativeName,
                     .Value = lang,
                     .Selected = (Model.UserInfoForm.Language = lang)
                 }))%>
<%: Html.ValidationMessageFor(Function(m) m.UserInfoForm.Language)%>

Where languages is a list of strings defined in the view e.g. "en", "fr", "de"


The problem is that the user can submit a value that is not inside the drop down list (e.g. with javascript, inspect element or not use a browser e.g. fiddler)

How do you validate the selected item, ensuring that it exists in the drop down list?

I am aware of validation attributes such as <StringLength> and <Required>, and I use If ModelState.IsValid Then in the action. Is there a ready made attribute stating where the validator should look for a list of allowed values?

Thanks for reading

4

1 回答 1

0

以自动验证方式在服务器端进行此验证是不可能的,因为服务器必须记住帖子之间的下拉列表中的选项。将下拉列表发送到 html 输出后,您将丢失可用的下拉列表数据。因此,您需要在服务器端重新创建可用选项以检查它们。

在我的项目中,我们倾向于在数据库内部进行这种正确性检查。在此示例中,他们将尝试将值插入应由外键链接的字段中。在此示例中,该字段是 Language,并且是引用表 LanugageAbbreviations 的外键。由于所选值“zz”没有外键,因此数据库在尝试插入时应该会失败。

如果您必须进一步推动验证,您可以随时检查下拉菜单中的有效值,即。

 [HttpPost]
 public ActionResult Index(AnimalViewModel model){
     CheckLanguageDropDownList(model, ModelState)
     ... 
 }

CheckLanguageDropDownList 在哪里

 private void CheckLanguageDropDownList(WordsModel viewModel, ModelStateDictionary modelState)
 {
        HashSet<String> validValues = new HashSet<string>(dataLayer.LanugageAbbreviationsRefrenceTable.GetActiveValues());
        if !validValues.Contains(viewModel.Lanuage)
            modelState.AddModelError("Invalid Language ","The language selected is invalid");
 }

如果您需要这样做,请确保以有意义的方式进行重构。

于 2013-06-16T04:51:31.533 回答