ASP.NET MVC Action Result、 html helper簡介

Net MVC的Controller提供了以下的Action Result作為回傳方式:

Result Class Description Base Controller Method
ViewResult 回傳Html的View View()
EmptyResult 沒有回傳
ContentResult 回傳大段文字 Content()
FileContentResult,
FilePathResult,
FileStreamResult
回傳檔案 File()
JavaScriptResult 回傳一段Javascript JavaScript()
JsonResult 回傳Json Json()
RedirectResult 回傳Url Redirect()
RedirectToRouteResult 回傳controller的action名稱 RedirectToRoute()
PartialViewResult 回傳 HTML PartialView()
HttpUnauthorizedResult 回傳HTTP 403狀態

html helper


MVC提供許多Html Helpers幫助開發者快速的產出通用的 Html 標籤,像是超連結或者表單元素,將Html tag以強行別的方式呈現,透過IDE來減少錯誤,但我個人其實還是比較偏好,自己寫Html的方式,這裡整理ㄧ些常用的Html Helper的寫法:

JS、CSS篇

@Url.Content(“~/Scripts/numberprice.js”)

@Url.Content(“~/Content/numberprice.css”)

超連結篇

@Url.Action(“Index”, “Home” , new { })

@Url.Content(“~/logo-welcome.png”)

@Html.ActionLink(“首頁”, “Index”, “Home”)

表單篇

@Html.TextBox("StudentName", null, new { @class = "form-control" })  
@Html.TextArea("Description", null, new { @class = "form-control" })  
@Html.CheckBox("isNewlyEnrolled", true)
@Html.DropDownList("StudentGender", 
                    new SelectList(Enum.GetValues(typeof(Gender))),
                    "Select Gender",
                    new { @class = "form-control" })
@Html.Hidden("StudentId")
@Html.Password("OnlinePassword")
@Html.Display("StudentName")
@Html.Label("StudentName")
@Html.Editor("StudentName")

@Html.ValidationMessageFor(model => model.Price, “”, new { @class = “text-danger” })

@using (Html.BeginForm(“Edit”, “Configure”)){

}

帶入html原生tag

@Html.Raw(“<div style=’color:red’>輸出字串</div>”)