筆記:Professional ASP.NET MVC 1.0

筆記:Professional ASP.NET MVC 1.0

1. Extension Method

只能宣告在非泛型的靜態型別內,要使用this,且不可與已有型別之方法簽名重覆。

image

 

2. ViewData & ViewModel

額外資訊可以透過ViewData傳遞,也可以重組一份ViewModel回傳。


//使用ViewData
public ActionResult Edit(int id)
{
      Dinner dinner = dinnerRepository.GetDinner(id);
      ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);
      return View(dinner);
}

<%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>

//使用模版
public class DinnerFormViewModel
{

        // Properties
        public Dinner Dinner { get; private set; }
        public SelectList Countries { get; private set; }

        // Constructor
        public DinnerFormViewModel(Dinner dinner)
        {
                Dinner = dinner;
                Countries = new SelectList(PhoneValidator.AllCountries, Dinner.Country);
        }
}

 <%= Html.DropDownList("Country", Model.Countries) %>

3. ModelState

利用ModelState回傳後,可以在頁面上利用Html.ValidationSummary顯示全部錯誤訊息,但也可以利用Html.ValidationMessage 顯示單項錯誤訊息(可覆寫)。


ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
 //列出所有錯誤訊息
<%= Html.ValidationSummary("Please correct the errors and try again.") %>

//覆寫錯誤訊息
<%= Html.ValidationMessage("EventDate", "*")%>

顯示結果:

190-41266434c0308b91

註: CSS 會自動套上 input-validation-error

 

 

 

4. 在ASP.NET MVC中,使用非同步回傳的方式:

Ajax.ActionLink("顯示字串", Action, Controller, Params, AjaxOptions)

AjaxOptions可包含回傳後要更新的目標ID,或是要執行的方法……等等

6ff845217268a5391c4a594592f90660


	<%= Ajax.ActionLink( "RSVP for this event", "Register", "RSVP", 
			new { id=Model.DinnerID },
			new AjaxOptions { UpdateTargetId = "rsvpmsg", OnSuccess = "animateRSVPMessage" })
	%>
	<script type="text/javascript">
		function animateRSVPMessage() 
		{
			$("#rsvpmsg").animate({ fontSize: "1.5em" }, 400);
		}
	</script>

 

5. RenderPartial

利用RenderPartial可以更方便的整理顯示樣版,但是已有的View和Partial名稱不可重覆,不然會當機。

 

相關連結:

Extension Methods (C# Programming Guide)

範例網站:NerdDinner

免費書籍及範例程式:Free ASP.NET MVC eBook Tutorial