あなたの2番目の質問に答えるには:MVCにはすでに組み込まれている検証が付属しています。
プロパティを必須にするには、ViewModelの属性で注釈を付けます。 resxファイルのキーを参照してカスタムエラーメッセージを指定することもできます。このキーには、プロパティの名前のプレースホルダが必要です。
例:
DataAnnotationsResources.resx
<data name="RequiredAttribute_ValidationError" xml:space="preserve">
<value>The {0} field is required.</value>
</data>
using System.ComponentModel.DataAnnotations;
public class ExampleCreateViewModel {
// Name is required for create!
[Required(ErrorMessageResourceType = typeof(DataAnnotationsResources), ErrorMessageResourceName = "RequiredAttribute_ValidationError")]
public string Name {get; set;}
}
星印で必要なフィールドをレンダリングするために、あなたは、HTMLヘルパーのために、以下の拡張メソッドを使用することができます。これは組み込みのHtml.LabelForヘルパーとYAML ym-required
クラスを使用してアスタリスクをスタイルします。
/// <summary>
/// Renders a Label for the Property
/// If [DisplayName] Attribute was set, it uses it as Translation Key
/// Else it uses the Property Name as label
/// If Required Attribute was set and <see cref="showHint"/> == <code>true</code>, attaches an red asterix * to the label
/// </summary>
/// <param name="html">HTML Helper object.</param>
/// <param name="metaDataAccessor">Lambda to access the property that contains the metadata (DisplayName, Required Attributes)</param>
/// <param name="forFieldAccessor">Lambda to set the property that is referenced by the "for" HTML attribute of the <label> tag</param>
/// <param name="showHint">Set to <code>false</code> to never show the red asterix * even if the Property is required (e.g. not nullable value Properties like <code>bool</code>)</param>
public static MvcHtmlString LabelForPlusHint<TModel, TMetaDataValue, TForFieldValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TMetaDataValue>> metaDataAccessor,
Expression<Func<TModel, TForFieldValue>> forFieldAccessor,
bool showHint = true) {
var metadata = ModelMetadata.FromLambdaExpression(metaDataAccessor, html.ViewData);
var label = html.LabelFor(forFieldAccessor).ToHtmlString();
if (metadata.IsRequired && showHint) {
label = label.Replace("</label>", "<sup class=\"ym-required\">*</sup></label>");
}
return new MvcHtmlString(label);
}
public static MvcHtmlString LabelForPlusHint<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> metaDataAccessor, bool showHint = true) {
return LabelForPlusHint(html, metaDataAccessor, metaDataAccessor, showHint);
}
使用例:@Html.LabelForPlusHint(m => m.Name)
必須の「名前」属性のラベルをレンダリングする。
MVCサイトにアクセスして、基本を学ぶことを強くお勧めします。 –
2番目の質問に答えるには、FYIndexというモデルを使用しているようです。 FYIndexモデルで必要な各フィールドに[必須]を追加します。 – w0ns88
追加4):[jQuery Autocomplete](https://jqueryui.com/autocomplete/)を使用できます。 –