Receive JSON from external server, parse it and save it to local database with MVC2

点点圈 提交于 2019-12-24 02:36:08

问题


I need to build a MVC2 project that can receive JSON ({"Address":"Streetname","Age":42"}) which is sent from an external server, parse it and save it to my local database (maybe with the help of a model?).

As I have never done this before, I am unsure about how to handle it. I would need some pointers about which technique it is recommended in this case (Linq to sql, Entity Framework, ADO.NET Entity Framework) and how to receive the JSON string (ActionMethod, or maybe in the Controller?) and save it localy (automatically, on receive).

Links to right documentation would be much appreciated, as I don't have a lot of time to read through all the beginners' tutorials.


回答1:


If you're really looking for something super simple, it can be as easy as this if you use MVC 3, which has built in JSON model binding for controller action parameters.

public class ContactController : Controller
{
    [HttpPost]
    public void SaveContact(Contact contact)
    {
        var context = new MyDataContext();
        context.Contacts.InsertOnSubmit(contact);
        context.SubmitChanges();
    }
}

I'm using LinqToSql in this example. Unless you start having domain logic or more complex entities it's really all you need.

For MVC 2, you need to download the Futures library and add this to your application startup.

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

You can find details here.



来源:https://stackoverflow.com/questions/5922206/receive-json-from-external-server-parse-it-and-save-it-to-local-database-with-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!