2015-01-07 37 views
1

C# MVC中,您可以使用模型綁定來自動將變量分析到模型。C#MVC將字符串中的變量綁定到模型

public class RegistrationForm { 
string Name {get;set;} 
string Address {get;set;} 
} 

public ActionResult Register(RegistrationForm register) { 
... 
} 

如果我通過了NameAddress變量,它們在register對象直接可用。

如果您有字符串中的變量,是否可以手動調用此綁定? EG:

var s = "name=hugo&address=test"; 

//dosomething to get RegistrationForm register 

//register.Name == hugo 

我知道我能得到一個NameValueCollectionHttpUtility.ParseQueryString(s);,然後使用反射來得到RegistrationForm屬性和檢查值存在,但我希望我可以用實際結合的方法MVC使用。

+0

請,如果你編輯我的問題不要改變它的意思。 –

回答

1

你可以嘲笑的HttpContext傳遞到Modelbinding喜歡這裏

http://www.jamie-dixon.co.uk/unit-testing/unit-testing-your-custom-model-binder/

var controllerContext = new ControllerContext(); 
//set values in controllerContext here 
var bindingContext = new ModelBindingContext(); 
var modelBinder = ModelBinders.Binders.DefaultBinder; 
var result = modelBinder.BindModel(controllerContext, bindingContext) 
+0

謝謝,那正是我所需要的。不幸的是,使用反射的工作更多(實際上更多)。我基本上是從頭構建一個全新的頁面請求來綁定這些值。 –

1

基於您的ViewModelRegistrationForm類)的Property Name的MVC綁定工作。

所以你絕對正確的,如果你使用GET HTTP方法從字符串的屬性綁定就可以直接這樣寫:

http://yourSite.com/YourController/Register?Name=hugo&Address=test

這是區分大小寫的,要小心。

或者,如果您使用剃刀生成鏈接,你可以把它寫更清晰的方式:

@Url.Action("Register", new { Name = "hugo", Address = "test"}) 
+0

是的,我知道我是對的:)但我沒有從查詢字符串或POST中獲取值,我將它們放入字符串變量中。他們錯誤地編輯了我的問題。 –

+0

好的,你的意思是在'js'變量中?你也可以用'js'來完成。 'window.location.href ='http://yourSite.com/YourController/Register?'+ s;'但不要忘記大小寫。 –

+0

@teovankot:不,一個C#字符串。 – Guffa

0

你可以將字符串轉換爲JSON對象,然後可以使用序列化程序將JSON對象解析爲您的模型。

0

@馬爾科姆的親屬是我所要求的,所以他得到了學分。但我仍然用反思結束了,因爲在我看來,它看起來更清晰,並且更容易理解正在發生的事情。

var result = HttpUtility.ParseQueryString(strResponse); 
Type myType = GetType(); 
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties()); 
foreach (PropertyInfo prop in props) 
{ 
    try 
    { 
     prop.SetValue(this, 
      Convert.ChangeType(result[prop.Name], prop.PropertyType, CultureInfo.InvariantCulture), 
      null); 
    } 
    catch (InvalidCastException) 
    { 
     //skip missing values 
    } 
    catch (Exception ex) 
    { 
     //something went wrong with parsing the result 
     new Database().Base.AddErrorLog(ex); 
    } 
} 

免責聲明 這對我的作品,因爲只有字符串和小數和需要什麼。這不像MVC模型綁定器。

相關問題