简体   繁体   English

如何使用依赖注入创建新对象

[英]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. 然后将其作为JSON传递到控制器。

How can I create a new object from this JSON to insert into the DB that I have, without doing 我如何通过此JSON创建一个新对象以插入到我拥有的数据库中,而无需这样做

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. 一种将json作为参数的操作方法。
  • Use the JsonConvert.DeserializeObject method (I have supposed that you use the Newtonsoft.Json library, the most used JSON framework for .NET. 使用JsonConvert.DeserializeObject方法(我假设您使用的是Newtonsoft.Json库,该库是.NET使用最多的JSON框架。
  • 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. 最后但并非最不重要的一点是,此方法返回一个View。 This is optional, you can define another return type and return whatever you want. 这是可选的,您可以定义其他返回类型并返回所需的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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