Search code examples
asp.net-coreasp.net-core-mvc

Two different buttons that save to two different databases in one view. ASP.NET Core


  1. When I press button id="submit", AddOrEdit in the controller does get launched and saves to database successfully

  2. When I press button id="submit2" SubmitDB in the controller is supposed to be called, but it doesn't get called. In fact, id="submit" AddOrEdit does get called again.

Please help - I think the problem is here:

//GET:Category/AddOrEdit
public IActionResult AddOrEdit(int id = 0)
{
    try
    {
        if (id == 0)
            return View(new CategoryModel());
        else
            return View(_context.Category.Find(id));
    }
    catch (Exception)
    {
        throw; 
    }
}

View (AddOrEdit)

<div class="row">  
<div class="col-md-7">
 <div class="widget p-5">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
           <input type="hidden" name="CategoryId" value="@Model.CategoryId" /> 
            <div class="mb-3">
                <div class='e-btn-group custom-rbt-group'>
                    <input type="radio" id="radioleft" name="Type" value="Expense"                                  checked="@(Model.Type=="Expense")" />
                    <label class="e-btn" for="radioleft">Expense</label>
                    <input type="radio" id="radiomiddle" name="Type" value="Income"   checked="@(Model.Type=="Income")" />
                    <label class="e-btn" for="radiomiddle">Income</label>
                </div>
                <span asp-validation-for="Type" class="text-danger"></span>
            </div>

 <div class="mb-3">
                <ejs-textbox id="title" placeholder="Title" ejs-for="Title" floatLabelType="Always"></ejs-textbox>
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="mb-3">
                <ejs-textbox id="icon" placeholder="Icon" ejs-for="Icon" floatLabelType="Always"></ejs-textbox>
                <span asp-validation-for="Icon" class="text-danger"></span>
            </div>
            @* <div class="mb-3">
                <ejs-button id="submit" asp-action="AddOrEdit" asp-controller="Category" type="submit" content="Submit" cssClass="e-success"></ejs-button>
            </div> *@
           <div class="mb-5">
                <ejs-button id="submit2" asp-action="AddOrEdit" asp-controller="Category" content="DB Submit" cssClass="e-success"></ejs-button>
 <ejs-button id="submit2" onclick="Test" content="DB Submit" cssClass="e-success"></ejs-button> 
            </div> 
        </form>
    </div>
    
</div>
<div class="col-md-5" style="background-color:#212b36">
    <div class="widget h-100 d-flex justify-content-center align-items-center" style="background-color:#212b36">
        
        <i class="fa-solid fa-shapes fa-spin fa-spin-reverse fa-2xl"></i>
    </div>
</div>
function Test(args) { debugger; }

Category controller:

namespace SyncFusion_Project.Controllers
{
    public class CategoryController : Controller
    {
        private readonly ApplicationDbContext _context;

        public CategoryController(ApplicationDbContext context)
        {
            _context = context;
        }
    
        // GET: Category
        public async Task<IActionResult> Index()
        {
            return View(await _context.Category.ToListAsync());
        }

        public async Task<IActionResult> Index2()
        {
            return View(await _context.Category.ToListAsync());
        }

        // GET: Category/AddOrEdit
        public IActionResult AddOrEdit(int id = 0)
        {
            try
            {
                if (id == 0)
  
                return View(new CategoryModel());

            else
                return View(_context.Category.Find(id));
        }
        catch (Exception)
        {
             throw; 
        }
    }

    // POST: Category/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddOrEdit([Bind("CategoryId,Title,Icon,Type")] CategoryModel categoryModel)
    {
        if (ModelState.IsValid)
        {
            if (categoryModel.CategoryId == 0)
                _context.Add(categoryModel);
            else
                _context.Update(categoryModel);

            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        return View(categoryModel);
    }     

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> SubmitBD([Bind("TransactionId,CategoryId,Amount,Note,Date")] Transaction transaction)
    {
       if (ModelState.IsValid)
       {
          if (transaction.TransactionId == 0)
              _context.Add(transaction);

          await _context.SaveChangesAsync();

          return RedirectToAction(nameof(Index));
      }  

      return View(transaction);
}

Solution

  • You do not say which controller and action the "submit2" calls

    So I guess he is a little bit confused.

    You should try to call the action with url.action like so:

    <button type="button" id="submit" onclick="submitForm('AddOrEdit')" 
    class="e-success">Submit</button>
    <button type="button" id="submitDB" onclick="submitForm('SubmitDB')" 
    class="e-success">DB Submit</button>
    
    <script>
    function submitForm(action) {
    var form = document.getElementById('categoryForm');
    form.action = '@Url.Action(action, "Category")';
    form.submit();
    }
    </script>
    

    the code will call submit form and pass the name of action you desire to call and submit the form