Asp.net MVC中關於Razor問題的解決方案

來源:互聯網
上載者:User
這篇文章主要給大家介紹了關於Asp.net MVC中Razor常見的問題與解決方案,文中通過範例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。

前言

最近在學習Asp.net MVC Razor,在使用中遇到了不少的問題,所以想著總結下來,沒有經驗的童鞋就是這樣磕磕碰碰出來的經驗。話不多說,來一起看看詳細的介紹:

一、Datatype的錯誤提示訊息無法自訂

這也許是Asp.net MVC的一個Bug。ViewModel中定義了DataType為Date欄位:


[Required(ErrorMessage = "Birthday must be input!")][DataType(DataType.Date, ErrorMessage = "Please enter a date like(2017-07-19).")]public DateTime BirthDay { get; set; }

Razor產生的HTML如下:


<input name="BirthDay" class="form-control" id="BirthDay" type="text" value="" data-val-required="Birthday must be input!" data-val="true" data-val-date="欄位 BirthDay 必須是日期。">

Required的錯誤訊息和定義的一樣,而DataType的訊息卻沒有??既然DataType有自訂訊息的公開屬性為啥不起作用?如果有知道的歡迎留言。

解決方案:

通過Javascript在頁面Load的時候替換掉原來的訊息。


$("#txtDesignatedDate").attr('data-val-date', 'Please enter a date like(2017/1/1)');

二、d-MMM-yy格式的英文日期在IE中驗證出錯,而在Chrome中沒問題

Razor模型繫結設定如下:


@Html.LabelFor(m => m.BirthDay, new { @class = "col-md-2 control-label" }) @Html.TextBoxFor(m => m.BirthDay, "{0:d-MMM-yy}", new { @class = "form-control" })

Edge測試情況:顯示日期不對的錯誤訊息。

Chrome測試情況:居然沒有錯誤提示!!

如果是英文以外同樣格式的日期,都會顯示日期不對錯誤訊息。這到底怎麼回事?

官網(http://jqueryvalidation.org/date-method/)其實也有說明:

翻看JS代碼:


 // http://docs.jquery.com/Plugins/Validation/Methods/datedate: function( value, element ) { return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());}, // http://docs.jquery.com/Plugins/Validation/Methods/dateISOdateISO: function( value, element ) { return this.optional(element) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value);},

dateISO也只支援yyyy-MM-dd 或者yyyy/MM/dd格式的驗證。沒辦法只能重寫一個驗證方法覆蓋原來的。

解決方案:


(function ($) { $.validator.methods.date = function (value, element) { return this.optional(element) || DateCheck(value); }}(jQuery));

自訂一個DateCheck函數就可以了。

三、DropDownList設定預設選擇項偶爾會無效

Action端設定:


return View(new RegisterViewModel { BirthDay = DateTime.Now, BirthCity = City.Shanghai });

View端設定:


@Html.DropDownListFor(m => m.BirthCity, new SelectListItem[] { new SelectListItem{ Text="Jiangxi",Value="1"}, new SelectListItem{ Text="Beijing",Value="2"}, new SelectListItem{ Text="Shanghai",Value="3"}, new SelectListItem{ Text="ShengZhen",Value="4"},}, new { @class = "form-control" })

偶爾這樣的設定無法選擇Action中設定的選項,如果有知道原因的歡迎留言。

解決方案:用SelectList替代SelectItem列表。


@Html.DropDownListFor(m => m.BirthCity, new SelectList(new SelectListItem[] { new SelectListItem{ Text="Jiangxi",Value="1"}, new SelectListItem{ Text="Beijing",Value="2"}, new SelectListItem{ Text="Shanghai",Value="3"}, new SelectListItem{ Text="ShengZhen",Value="4"},}, "Value", "Text", Model.BirthCity), new { @class = "form-control" })

四、密碼輸入自動提示在Chrome中無法禁止

autocomplete = "off"在Chrome58以後都無效了。這個是瀏覽器的問題沒辦法了。

五、Disabled的控制項值不上傳給伺服器

解決方案:通過Javascript在submit之前將控制項的Disabled屬性刪除,submit完成之後再複原Disabled屬性。

六、Html.HiddenFor()的控制項值不更新

由於HiddenFor預設先使用ModelState的資料,所以在ModelState驗證失敗的情況下,重新載入畫面可能HiddenFor的控制項資料是舊的。

解決方案:


ModelState.Clear();

七、List與Dictionary的資料Razor如何綁定

ViewModel屬性:


public List ListTest { get; set; }public Dictionary> DicTest { get; set; }

View端綁定:


@for (int i = 0; i < Model.ListTest.Count; i++){ @Html.TextBoxFor(m => m.ListTest[i].Name, new { @class = "form-control" }) @Html.TextBoxFor(m => m.ListTest[i].Phone, new { @class = "form-control" })}


@for (int i = 0; i < Model.DicTest.Count; i++){ string key = Model.DicTest.Keys.ElementAt(i); < input type="hidden" name="DicTest[@i].Key" value="@key" /> for (int j = 0; j < Model.DicTest[key].Count; j++) { @Html.TextBox($"DicTest[{i}].Value[{j}].Name", Model.DicTest[key][j].Name, new { @class = "form-control" }) @Html.TextBox($"DicTest[{i}].Value[{j}].Phone", Model.DicTest[key][j].Phone, new { @class = "form-control" }) }}

產生的Html如下:


<input name="ListTest[0].Name" class="form-control" id="ListTest_0__Name" type="text" value="lxb1"><input name="ListTest[0].Phone" class="form-control" id="ListTest_0__Phone" type="text" value="123"><input name="ListTest[1].Name" class="form-control" id="ListTest_1__Name" type="text" value="lxb2"><input name="ListTest[1].Phone" class="form-control" id="ListTest_1__Phone" type="text" value="1234"><input name="ListTest[2].Name" class="form-control" id="ListTest_2__Name" type="text" value="lxb3"><input name="ListTest[2].Phone" class="form-control" id="ListTest_2__Phone" type="text" value="12345">


<input name="DicTest[0].Key" type="hidden" value="JX"><input name="DicTest[0].Value[0].Name" class="form-control" id="DicTest_0__Value_0__Name" type="text" value="lxb1"><input name="DicTest[0].Value[0].Phone" class="form-control" id="DicTest_0__Value_0__Phone" type="text" value="123"><input name="DicTest[0].Value[1].Name" class="form-control" id="DicTest_0__Value_1__Name" type="text" value="lxb2"><input name="DicTest[0].Value[1].Phone" class="form-control" id="DicTest_0__Value_1__Phone" type="text" value="1234">  <input name="DicTest[1].Key" type="hidden" value="SZ"><input name="DicTest[1].Value[0].Name" class="form-control" id="DicTest_1__Value_0__Name" type="text" value="lxb3"><input name="DicTest[1].Value[0].Phone" class="form-control" id="DicTest_1__Value_0__Phone" type="text" value="12345"><input name="DicTest[1].Value[1].Name" class="form-control" id="DicTest_1__Value_1__Name" type="text" value="lxb4"><input id="DicTest_1__Value_1__Phone" class="form-control" value="123456" name="DicTest[1].Value[1].Phone">

其中控制項的name很重要。

List: viewmodelpropertyname[index].modelpropertyname 格式。

Dictionary:key設定為viewmodelpropertyname[index].Key,Value設定為viewmodelpropertyname[index].Value

八、盡量多使用EditorFor

比如將第7點的DicTest使用EditorFor。首先需要在Shared或者Controller自身檔案夾下建立EditorTemplates檔案夾,然後在EditorTemplates檔案夾中添加分部頁。代碼如下:


@using MVCDemo.Models; @model List @for (int i = 0; i < Model.Count; i++){ @Html.TextBoxFor(m => m[i].Name, new { @class = "form-control" }) @Html.TextBoxFor(m => m[i].Phone, new { @class = "form-control" })}

調用版面設定:

List的時候


@Html.EditorFor(m => m.ListTest, "_PartialPerson", $"ListTest")

Dictionary的時候


@for (int i = 0; i < Model.DicTest.Count; i++){ string key = Model.DicTest.Keys.ElementAt(i); <input type="hidden" name="DicTest[@i].Key" value="@key" /> @Html.EditorFor(m => m.DicTest[key], "_PartialPerson", $"DicTest[{i}].Value")}

產生的HTML:


<p class="col-md-10">  <input name="ListTest[0].Name" class="form-control" id="ListTest_0__Name" type="text" value="lxb1"><input name="ListTest[0].Phone" class="form-control" id="ListTest_0__Phone" type="text" value="123"><input name="ListTest[1].Name" class="form-control" id="ListTest_1__Name" type="text" value="lxb2"><input name="ListTest[1].Phone" class="form-control" id="ListTest_1__Phone" type="text" value="1234"><input name="ListTest[2].Name" class="form-control" id="ListTest_2__Name" type="text" value="lxb3"><input name="ListTest[2].Phone" class="form-control" id="ListTest_2__Phone" type="text" value="12345"></p>


<p class="col-md-10">  <input name="DicTest[0].Key" type="hidden" value="JX"><input name="DicTest[0].Value[0].Name" class="form-control" id="DicTest_0__Value_0__Name" type="text" value="lxb1"><input name="DicTest[0].Value[0].Phone" class="form-control" id="DicTest_0__Value_0__Phone" type="text" value="123"><input name="DicTest[0].Value[1].Name" class="form-control" id="DicTest_0__Value_1__Name" type="text" value="lxb2"><input name="DicTest[0].Value[1].Phone" class="form-control" id="DicTest_0__Value_1__Phone" type="text" value="1234">  <input name="DicTest[1].Key" type="hidden" value="SZ"><input name="DicTest[1].Value[0].Name" class="form-control" id="DicTest_1__Value_0__Name" type="text" value="lxb3"><input name="DicTest[1].Value[0].Phone" class="form-control" id="DicTest_1__Value_0__Phone" type="text" value="12345"><input name="DicTest[1].Value[1].Name" class="form-control" id="DicTest_1__Value_1__Name" type="text" value="lxb4"><input name="DicTest[1].Value[1].Phone" class="form-control" id="DicTest_1__Value_1__Phone" type="text" value="123456"> </p>

這樣就簡化了不少,也到達了重用。

總結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.