简体   繁体   中英

ASP.NET MVC 5 TryUpdateModel not allowing & in string

Starting with an original string of: "Text=AB&C", this value is passed through the HttpUtility.ParseQueryString to create a NameValueCollection.

Then to create the IValueProvider for the TryUpdateModel, the NameValueCollection creates a new NameValueCollectionProdvier.

At this point in the NameValueCollectionValueProvider, the Key becomes Text and the Value still remains AB&C.

When the TryUpdateModel is called passing in the values, the Text changes from AB&C to AB.

Any thoughts on why this might be?

Here is the code:

e is from a foreach that was passed in to the Controller ActionResult model value

foreach (string e in model.Elements)
{
    string queryString = HttpUtility.UrlDecode(e);
    var model = new Model();
    NameValueCollection nameValues = HttpUtility.ParseQueryString(queryString);
        // nameValues = {Text=AB&C} at this point
    var provider = new NameValueCollectionValueProvider(nameValues, System.Globalization.CultureInfo.CurrentUICulture);
        // provider = NameValueCollectionValueProvider at this point
        // It's _values has a Count=1
        // which at index [0] has this value {[Text, System.Web.Mvc.NameValueCollectionProvider+ValueProviderResultPlaceholder]}
        // which has a Key of "Text"
        // and a Value of System.Web.Mvc.NameValueCollectionProvider
        // within that Value, it's broken down with some properties
        // System.Web.Mvc.NameValueCollectionProvider
        // _validatedCollection and _unvalidatedCollection both have a value of Text=AB&C
        // but I see now that the ValidatedResult and the UnvalidatedResult both have a value of AB
    TryUpdateModel(model, provider);

The model's Text value is declared as public string Text { get; set; } public string Text { get; set; } public string Text { get; set; } so the TryUpdateModel does find the matching Text declaration.

Updated:

I found that within the NameValueCollectionValueProvider, the provider's Value has an _unvalidatedCollection and a _validatedCollection with my expected result of Text=AB&C but the UnvalidatedResult and the ValidatedResult within the provider both have a value of AB.

It seems that the provider is removing values after the &.

Can the provider itself be further encoded to maintain the & in the string?

你需要,当你正在构建的URL编码和解码,当你试图读取网址参数string queryString = "Text=" + HttpUtility.UrlEncode("AB&C") ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM