简体   繁体   中英

String to object (MVC model binding)

So I have a string. And I have a Type, and a property name. Is it possible to convert the string to an object according to the current model binding rules for Type and propertyName in a controller?

For example, I have this model:

class foo {

  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM dd yyyy}")]
  public DateTime Date { get; set; }
}

, and this string:

"01 01 1970",

and I have the value of typeof(foo), and I have the name of the property, "Date".

How can I convert it to an object (DateTime) according to the current model binding rules and model rules?

Thus, I need something like:

object GetModelProperty(string input, Type modelType, string propertyName) { ... }

Thanks!

You can convert the view model to Json object most cases followed with MVC

in this case you need not convert the json data in your view.

you can use something like this code

var date = Date;
var viewModel = new ViewModel();
var serializer = new JavaScriptSerializer();
viewModel.JsonData = serializer.Serialize(data);

return View("viewname", viewModel);

and then in view you use

<%= Model.JsonData %>

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