简体   繁体   中英

How do I create a new object using dependency injection

At the moment I have a form where users create a new object. This is then passed to the controller as JSON.

How can I create a new object from this JSON to insert into the DB that I have, without doing

var x = new CustomObject {
    ExampleField = JSONProperty,
    ExampleField2 = JSONProperty2
};
repo.Create(x);

In general, you need something like this:

[HttPost]
public ActionResult CreateCustomer(string json)
{
    var customer = JsonConvert.DeserializeObject<Customer>(json);
    repo.Create(customer);
    return View(customer);
}
  • An action method that takes as a parameter your json.
  • Use the JsonConvert.DeserializeObject method (I have supposed that you use the Newtonsoft.Json library, the most used JSON framework for .NET.
  • The customer hew is an hypothetical object. You can follow the same approach for any custom object.
  • Last but not least this method return a View. This is optional, you can define another return type and return whatever you want.

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