標籤

ASP.NET MVC (29) Visual C# (15) JQuery (10) Plugins (8) JQuery Plugins (6) JavaScript (6) MySQL (5) CSS (4) LinQ (4) Mac OS (4) CentOS (3) Design Pattern (3) Entity Framework (3) IIS (3) Python (3) Windows (3) php (3) Docker (2) LAMP (2) SQL Server (2) WCF (2) .NET (1) .NET Core (1) AWS (1) Browser (1) GIS (1) IE (1) Internet Security (1) Linux (1) Platform (1) React (1) SEO (1) Testing (1) VMware (1) Windows 7 (1) cookie (1) curl (1) laravel (1) phpBB (1) session (1) 中古屋 (1) 透天 (1) 閒言閒語 (1) 面試 (1) 鳥松 (1)
顯示具有 ASP.NET MVC 標籤的文章。 顯示所有文章
顯示具有 ASP.NET MVC 標籤的文章。 顯示所有文章

2013年11月13日 星期三

[ASP.NET MVC] 如何在MVC中支援讀取靜態html;htm 檔案

在route規則中加入以下規則

routes.IgnoreRoute("*.html")

原理是只要看到*.html的要求,則忽略路由規則,不會去找對應的Controller -> Action



[Reference]:

Add Static HTML file to Root of Azure MVC App

2013年11月12日 星期二

[ASP.NET MVC] 如何將物件序列化為Json格式,不使用Controller.Json()方法。

在Controller中我們可以輕鬆使用return Controller.Json(obj)方法來將obj序列化成Json格式,

但如果要在其他地方做也許不行,此時可以使用下列方式:

(new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(obj);

來將obj序列化成Json格式,注意回傳是string。

----

更新:

此種方法會讓<br>轉換為\u003cbr\u003e ,推薦使用Json.NET

var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj)

如果objJson中含有Html Tag (例如<br>),則需以變數方式寫在HTML TAG中:

<html>
    <div id="D">@objJson</div>
</html>

之後使用JQuery取出:
    var aJson = $.parseJSON($('div#D').text());

這樣aJson 就不會出錯了



Reference :
JavaScriptSerializer 類別

Json.NET


2013年5月15日 星期三

[ASP.NET MVC][IIS]在應用程式層級之外使用註冊為 allowDefinition='MachineToApplication' 的區段發生錯誤。錯誤的原因可能是虛擬目錄尚未在 IIS 中設定為應用程式


針對網站做發行時發生下列錯誤訊息導致無法發行:

在應用程式層級之外使用註冊為 allowDefinition='MachineToApplication' 的區段發生錯誤。錯誤的原因可能是虛擬目錄尚未在 IIS 中設定為應用程式

網路上找了一下,大致原因是存在了重複的WebConfig檔案,下意識把整個obj目錄砍了再發行一次就沒問題了,詳細原因沒研究。


保哥部落格有相關資訊:

ASP.NET MVC 建置部署套件後無法 MvcBuildViews 的解法

Reference:

Asp.net MVC 建置發行時出現錯誤訊息:錯誤的原因可能是虛擬目錄尚未在 IIS 中設定為應用程式。






















2011年10月16日 星期日

[ASP.NET MVC] 快取( Cache ) 的機制

MVC 中有內建屬性可以控制是否要再Client端作cache,也有Server-cache的機制,如果我們是某個partialView要快取在server,則直接在Action上使用:
[System.Web.Mvc.OutputCache(Duration = 60)]


或者直接操作比較底層的東西:


---
保哥這篇很棒:


2011年9月19日 星期一

[ASP.NET MVC] 在View中使用預設的客戶端驗證

Using the client side validation in ASP.NET MVC3 without Model.
---
我既想要使用ASP.NET MVC的客戶端驗證,但是我又不想綁定資料模型,其實很簡單,只需將每個想要驗證的加上以下屬性:
  • data-val = true
  • data-val-(required|regex|range|equalto|remote|length|number)="顯示的錯誤訊息"

然後除了require不用規則,其他規則根據下列來加入:
  • data-val-regex-pattern
  • data-val-range-min
  • data-val-range-max
  • data-val-equalto-other
  • data-val-remote-url
  • data-val-remote-type
  • data-val-remote-additionalfield
  • data-val-length-min
  • data-val-length-max
例如我有個input名稱叫做keyword,他是屬於必要項目,那設定如下:
<input id="keyword" type="text" value="" name="keyword" data-val-required="關鍵字欄位為必要項。" data-val="true">

*注意true不能大寫為True

---
當然View中該引用的東西還是得引用:
1. 下面兩個js檔案
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.min.js"

2. @Html.BeginForm內部要加上:@Html.ValidationSummary(true)

---
Reference:



2011年8月25日 星期四

[ASP.NET MVC] 自訂模型繫結 (Custom Model Binder)

我想在ASP MVC中,是必須要了解的部分,尤其是"日期時間"資料型態應該是我們第一個會遇到的問題,關於日期時間:
http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx

Stack Overflow也有:
較簡單的範例

有時間再來寫實際實作過程...



2011年6月3日 星期五

[ASP.NET MVC] 在View中取得目前的Controller, Action 的名稱

MVC3使用方式:
ViewContext.Controller.ValueProvider.GetValue("action").RawValue

ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue

MVC2:
ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue

ViewContext.Controller.ValueProvider["id"].RawValue

Reference:

ASP.NET MVC - Current Action

2011年5月9日 星期一

[ASP.NET MVC] 使用者被鎖定下不可以使用ResetPassword()重置密碼

如果使用者已經被鎖定時(Lock)使用Membership中的ResetPassword()重置密碼會發生下列錯誤:

=====================================================

'/' 應用程式中發生伺服器錯誤。

使用者帳戶已鎖定。

描述: 在執行目前 Web 要求的過程中發生未處理的例外情形。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。

例外詳細資訊: System.Web.Security.MembershipPasswordException: 使用者帳戶已鎖定。

原始程式錯誤:

行 454:        private string ResetPWAndEmailToUserEmai(MembershipUser user) 行 455:        {                     行 456:            string newPW = user.ResetPassword(); //幫 行 457:            var message = new System.Net.Mail.MailMessage("xxxxxxxx@gmail.com", user.Email) 行 458:            {

原始程式檔: D:\0. My Program\Buddy\MvcBodyApp\MvcBodyApp\Controllers\AccountController.cs 行: 456
============================================

所以ResetPassword時還得先檢查


2011年5月4日 星期三

[ASP.NET MVC] 驗證字串的最小值

MVC 2 驗證模型中有限制字串長度上限的DataAnnotations
[StringLength(4, ErrorMessage = "The ThumbnailPhotoFileName value cannot exceed 4 characters. ")]

如果想要實作驗證字串長度下限可以參考:
http://www.tsjensen.com/blog/CommentView,guid,904052d4-8ee0-47b5-bacb-eb1788137233.aspx

MSDN: StringLengthAttribute 類別




2011年4月27日 星期三

[ASP.NET MVC] 禁止停用IE的網頁資料快取機制 (disable browser cache)

只要加上以下程式碼:

public class NoCacheAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);

            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();

            base.OnResultExecuting(filterContext);
        }
    }


之後在任何的Action或Class上方加上[NoCache]即可;

[NoCache]
public class AController : Controller
{
    [NoCache]
    public ActionResult Index()
    {
        return View();
    }
}


Reference:

asp.net mvc disable browser cache

2011年4月26日 星期二

[ASP.NET MVC] 升級MVC2 至 MVC3的工具 - ASP.NET MVC 3 Application Upgrad

ASP.NET MVC 3 Application Upgrad

這裡可以下載:
http://aspnet.codeplex.com/releases/view/59008

目前用了之後沒甚麼問題,有問題再說...

[ASP.NET MVC] 如何在使用JQuery載入部分檢視(Partial View)

How to load the Partial View using JQuery in ASP.NET MVC?
============================
假設部分檢視的路徑為~/Manager/Student/3,且一開始就載入部分檢視,只要在script中定義function:


jQuery(document).ready(function () {
    ajax_updatePartial('<%= Url.Content("~/Manager/Student/")%>' + '<%: Model.Id %>');
});
        
function ajax_updatePartial(path){
  $.ajax ({
    url: path,
    success: function(result) {
        $('#AjaxStudentInClassPartial').html(result);
        }
    });
return false;
}

2011年4月21日 星期四

[ASP.NET MVC] 如何在View中使用強型別DropDownListFor

How to use the strongly type "DropDownListFor" in View in ASP.NET MVC.
===============================================================
First, Assume I have two tables "Person,Weapon" both have relationship:

[Person]
{
    PersonID
    WeaponID
}

[Weapon]
{
    WeaponID
    WeaponName
}

---
OK, now I want to show the information of all the Person in database. I should write:
using (Entites db = new Entites())
            {
                var result = (from s in db.Person.Include("Weapon") select s).ToList();
                return View(result);
            }
            return View();


View:
<% foreach (var item in Model) { %>
        <%: Html.DropDownListFor(s=>s.Person.Where(a=>a.WeaponID == item.WeaponID).WeaponID , 
    new SelectList(MyApplication.Models.DropDownList.GetDropDownList(), "Value", "Text", item.WeaponID )%>    
><% } %>



Now we should write the class DropDownList with namespace MyApplication.Models:
class DropDownList
    {
        public List GetDropDownList()
        {
            List result = new List();
            result.Add(new System.Web.Mvc.SelectListItem
            {
                Value = "1",
                Text = "Apple"
            });
            result.Add(new System.Web.Mvc.SelectListItem
            {
                Value = "2",
                Text = "Milk"
            });
            return result;
        }
    }


In fact, GetDropDownList() Method can access the data via Weapon table in our database.

Reference:http://stackoverflow.com/questions/4312925/asp-net-mvc-dropdownlistfor-or-dropdownlist-with-strongly-typed-viewmodel

weak-type: http://ittecture.wordpress.com/2009/05/10/tip-of-the-day-208-asp-net-mvc-populating-dropdownlists-using-linq-to-sql/

Some discussion: http://stackoverflow.com/questions/1916462/dropdownlistfor-in-editortemplate-not-selecting-value

2011年4月17日 星期日

[ASP.NET MVC]直接在Controller中取得檔案的絕對路徑(Content or Script path)

通常我們在View中都會使用:1. Html Helper 2.Url Helper
那假設我們想要在Controller中直接取得Content或Script的絕對路徑(path)呢?


public ActionResult Image(string id)
{
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg");
    return base.File(path, "image/jpeg");
}

效能有差一點點就是了...

參考資料:

Can an ASP.Net MVC controller return an Image?

http://stackoverflow.com/questions/186062/can-an-asp-net-mvc-controller-return-an-image



[ASP.NET MVC]將form放在JqueryUI Dialog中post與validation失效的問題

這個問題害我卡了一個下午,如果我們將MVC的FORM使用JqueryUI Dialog包起來的話,他會把FORM移出Dialog,只要下面這個指令就可以解決:
   $('#dialog').parent().appendTo($('#PostForm'));

參考資料:

jQuery validation error inside the jQuery.UI.Dialog

2011年4月6日 星期三

[ASP.NET MVC]取得Server絕對路徑的幾種方式

目前網址上的URL:http://localhost:60786/Manage/CreateBoardActive

每個程式碼對應的結果:


    <%: HttpContext.Current.Server.MapPath("~/FileImageExtra/getOriginal/")%>
    D:\0. My Program\MvcApp\FileImageExtra\getOriginal\

    <%: System.Web.Hosting.HostingEnvironment.MapPath(@"~/FileImageExtra/getOriginal/") %>
    D:\0. My Program\MvcApp\FileImageExtra\getOriginal\

    http://<%= Request.Url.Authority%><%=Url.Action("getOriginal", "FileImageExtra")%>
    http://localhost:60786/FileImageExtra/getOriginal

    <%= Request.Url.AbsoluteUri%>
    http://localhost:60786/Manage/CreateBoardActive