2011-08-07 85 views
1

我想我已經找到了ASP.NET MVC控制器的參數人口ASP.NET MVC模型綁定錯誤

public JsonResult Lookup(
    string q_word, string primary_key, 
    int per_page, int page_num) 

如果q_word公佈值是空字符串錯誤,q_word會收到一個空字符串。而如果將這些參數打包在一起(DRY原則),則行爲不同,空字符串將變爲空。

public class LookupArg 
{ 
    public string q_word { get; set; } 

    public string primary_key { get; set; } 
    public int per_page { get; set; } 
    public int page_num { get; set; } 

    public string another_word { get; set; } 
} 


public JsonResult TesterA(
     string q_word, string another_word, string primary_key, 
     int per_page, int page_num) 
{ 
    return Json(
       new { q_word, primary_key, per_page, page_num, another_word}, 
       JsonRequestBehavior.AllowGet); 
} 

public JsonResult TesterB(LookupArg la) 
{ 
    return Json(
       new { la.q_word, la.primary_key, la.per_page, la.page_num, 
         la.another_word }, 
       JsonRequestBehavior.AllowGet); 
} 

http://localhost:19829/Product/TesterA?q_word=&primary_key=id&per_page=10&page_num=1&another_word= 有這樣的輸出:

{"q_word":"","primary_key":"id","per_page":10,"page_num":1,"another_word":""} 

http://localhost:19829/Product/TesterB?q_word=&primary_key=id&per_page=10&page_num=1&another_word= 有這樣的輸出:

{"q_word":null,"primary_key":"id","per_page":10,"page_num":1,"another_word":null} 

我想這太,但無濟於事,相同的輸出,q_word和another_word是仍爲空

public JsonResult TesterB(
    [Bind(Include = "q_word, primary_key, per_page, page_num, another_word")] 
    LookupArg la) 

預計這種行爲?通過設計?如果價值來自對象或者不對,應該有什麼區別嗎?

回答

0

如果您想覆蓋自ASP.NET MVC 2以來的設計行爲(它不是ASP.NET MVC 1中的情況,您可以檢出following blog post),那麼可以使用[DisplayFormat]屬性來修飾屬性:

public class LookupArg 
{ 
    [DisplayFormat(ConvertEmptyStringToNull = false)] 
    public string q_word { get; set; } 

    ... 
} 
+0

那麼,工程:-)你是否有任何文章的鏈接,解釋一個字符串的基本原理,如果它是在對象 – Hao