locked
Post form to api controller to create new record RRS feed

  • Question

  • User2139392758 posted

    Best regards for all.

    I want to send a form to api controller that create a new record.

    In https://www.learnrazorpages.com/razor-pages/ajax/form-post there are this example:

    $.post('', $('form').serialize(), function () {
        alert('Posted using jQuery');
    });
    

    In my case is:

    $.post(url, $('#frm-config').serialize(), function () {
        alert("Data is saved");
    });
    The api controller works fine when update data but I don't know how handle it when is a new record or the first record to be created,
     
    I tried to  ask for _context.Entry(Config).State in a switch statement, but allways is Detached.
     
    This is the api controller:
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Tienda.Data;
    using Tienda.Models;
    
    namespace Tienda.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ConfigController : ControllerBase
        {
            private readonly TiendaDbContext _context;
    
            public ConfigController(TiendaDbContext context)
            {
                _context = context;
            }
    
            [BindProperty]
            public Config Config { get; set; }
    
            [HttpPost]
            public async void PostConfig()
            {
                if (ModelState.IsValid)
                {
                    _context.Entry(Config).State = EntityState.Modified;
                    await _context.SaveChangesAsync();
                }
            }
        }
    }
    
    In the OnGet method of PageModel I create a new instance of Config when FirstOrDefault method returns null.
    This is PageModel (abreviated):
    using System.Linq;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Tienda.Data;
    using Tienda.Models;
     
    namespace Tienda.Pages
    {
        public class ConfigModel : PageModel
        {
            public readonly TiendaDbContext _context;
     
            [BindProperty]
            public Config Config { get; set; }
     
            public ConfigModel(TiendaDbContext context)
            {
                _context = context;
            }
     
            public void OnGet(int? id)
            {
                Config = _context.Config.AsQueryable().FirstOrDefault();
                if (Config == null)
                {
                    Config = new Config();
                }
            }
        }
    }
    
    
    Thanks in advance for your help
    Saturday, July 11, 2020 10:03 PM

All replies

  • User-2054057000 posted

    You can just put a post action method that will be use for creating a new record in API in ASP.NET Core:

    [HttpPost]
    public Person Post([FromBody] Person per) {
        // insert the person in the database 
    }

    Next you need to simply call the above api method from your client application. The above method inserts the person in the database and also sends back the new person's records back to the client in JSON format.

    You can refer - API Controllers – Creating API in ASP.NET Core

    Sunday, July 12, 2020 3:57 AM
  • User2078676645 posted

    Hi,

    You need to modify the method of adding data in ConfigController. Because this method is used to modify the data.

    if (ModelState.IsValid)
                {
                    _context.Entry(Config).State = EntityState.Modified;
                    await _context.SaveChangesAsync();
                }

    Controller

    [Microsoft.AspNetCore.Mvc.Route("api/[controller]/")]
        [ApiController]
        public class ConfigController : ControllerBase
        {
            private readonly TiendaDbContext _context;
    
            public ConfigController(TiendaDbContext context)
            {
                _context = context;
            }
    
            [BindProperty]
            public Config Config { get; set; }
    
            [HttpPost("PostConfig")]
            public async void PostConfig([FromForm]string config)//Serialize config to json in view
            {
    //Nuget Newtonsoft,it can convert json to class or convert json to class in other methods.
                Config con= Newtonsoft.Json.JsonConvert.DeserializeObject<Config>(config);
                Console.WriteLine(con);
    //Determine model or add to database in some way
    var conf = _context.Config.AsQueryable().FirstOrDefault();
               
    if (conf== null)
               
    {
                    _context.configs.Add(con);
                    _context.SaveChanges();

               
    }else{
    if (ModelState.IsValid)
               
    {
    //set the data to be changed
                    _context
    .Entry(Config).State = EntityState.Modified;
                    await _context
    .SaveChangesAsync();
               
    }
    }
    } }

    Best Regards,

    Evern

    Monday, July 13, 2020 9:03 AM