1

In C# MVC you can use model binding to automatically parse variables to a model.

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

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

If I pass the Name and Address variables they are directly available in the register object.

Is it possible to call this binding manually if you have the variables in a string? EG:

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

//dosomething to get RegistrationForm register

//register.Name == hugo

I know I can get a NameValueCollection with HttpUtility.ParseQueryString(s); and then use reflection to get the properties of RegistrationForm and check if the values exists, but I was hoping I could use the actually binding method MVC uses.

1
  • Please, if you edit my question dont change it's meaning. Commented Jan 7, 2015 at 13:27

4 Answers 4

1

You could mock the HttpContext passed into Modelbinding like here

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that is what I needed. Unfortunately that is even more (A lot more, actually) work then using reflection. I'm basically building a whole new page request from scratch to bind the values.
1

MVC binding working based on Property Names of your ViewModel (RegistrationForm class).

So you absolutely right, if you use GET HTTP Method to bind your property from string you can write this directly:

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

It's case sensitive, be carefull.

Or if you use Razor to generate links you can write it more clear way:

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

8 Comments

Yes I know I'm right :) But I don't get the values from the query string or POST, I have them in a string variable. They edited my question wrongfully.
ok, you mean in js variable? You can also do it with js. window.location.href = 'http://yourSite.com/YourController/Register?'+s; but don't forget about case.
@teovankot: No, a C# string.
No, I mean a string myvariables = "name=hugo&address=test" I'm already in a controller/action and there I have variable which I want to parse to a model
I dont agree with "It's case sensitive"
|
0

You can convert the string to JSON object and then you can parse JSON object to your Model by using a Serializer.

Comments

0

@Malcolm's anwser is what I requested, so he gets the credits. But I still ended up doing it with reflection, because it looks a lot cleaner in my opinion and easier to understand what is going on.

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);
    }
}

Disclaimer This works for me because I only get strings and decimals and nothing is required. This is nothing like the MVC model binder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.