Home > database >  ajax post failed but controller & db data ok
ajax post failed but controller & db data ok

Time:09-07

im posting data to controller with partailview the controller receive valid data & store it in my DB but:

  1. im getting ajax failed Msg.

  2. im not getting a TempData displayed as expected ( i have one for results OK and else for error). Im not sure where to put my finger on .

    Index View

    @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

    function SubmitREgNews() { var data = { userName: $("#name").val(), UserMail: $("#email").val(), TermsOk: $("#bOk").val(), };

         $.ajax({
             type: 'POST',
             url: "/NewsLetter/Create",
             contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
             data: data,
    
             success: function(result) {
                 alert('Successfully received Data ');
                 console.log(result);
             },
             error: function() {
                 alert('Failed to receive the Data');
                 console.log(JSON.stringify(error));
                 console.log('Failed ');
             }
         });
     }
    

    Partial view @if (@TempData["ErrorMes"] != null) { @TempData["ErrorMes"] } @if (@TempData["regOk"] == null) {

         <div >
             <div >
                 <form id="studenteForm" novalidate >
                     <div asp-validation-summary="ModelOnly" ></div>
                     <div >
                         <label asp-for="userName" ></label>
                         <input asp-for="userName"  id="name" required />
    
                     </div>
                     <div >
                         <label asp-for="UserMail" ></label>
                         <input asp-for="UserMail" type="email"  id="email" />                                                    </div>
                     <div >
                         <label >
                             <input  id="bOk" asp-for="TermsOk" /> @Html.DisplayNameFor(model => model.TermsOk)
                         </label>
                     </div>
                     <div >
                         <button type="button"  onclick="SubmitREgNews();">Add </button>
                     </div>
                 </form>
             </div>
         </div>
         </div>
     }
    

    @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } controller

           public IActionResult _RegNews()
         {
             return PartialView();
         }
      [HttpPost]
     public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews )
         {
             var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
                 a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
    
             if ( ModelState.IsValid && IsNewUser==null)
             {
                 joinNews.JoinId = Guid.NewGuid();
                 joinNews.JoinDate = DateTime.Now;
                 _context.Add(joinNews);
                 await _context.SaveChangesAsync();
                 TempData["regOk"] = "You are  register";
                 return View("home/index");
                 }
             else
             {
                 TempData["ErrorMes"] = "You are allready register";
             }
             return PartialView("_RegNews", joinNews);
    
         }
    

CodePudding user response:

The reason you are getting ajax failed Msg may be that you are returning the wrong path "home/index". Paths in one controller that call a page in another controller should use "../home/index".

Also, Ajax doesn't change page elements. If you want to redirect to another page you can use Url.Action.

Like this:

Controller:

[HttpPost]

public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews)
{
    
    var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
        a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));

    if (ModelState.IsValid && IsNewUser == null)
    {
        joinNews.JoinId = Guid.NewGuid();
        joinNews.JoinDate = DateTime.Now;
        _context.Add(joinNews);
        await _context.SaveChangesAsync();
        TempData["regOk"] = "You are  register";
        return Json(new { redirectUrlOne = Url.Action("Index", "Home")});
    }
    else
    {
        TempData["ErrorMes"] = "You are allready register";
        return Json(new { redirectUrlTwo = Url.Action("_RegNews", "NewsLetter") });
    }
}

And your ajax:

$.ajax({
        type: 'POST',
        url: "/NewsLetter/Create",
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: data,

        success: function (result) {
              alert('Successfully received Data ');
              if (result.redirectUrlOne !== undefined) {
                    window.location.replace(result.redirectUrlOne);
              } else {
                    window.location.replace(result.redirectUrlTwo);
              }
              console.log(result);
       },
       error: function (error) {
              alert('Failed to receive the Data');
              console.log(JSON.stringify(error));
              console.log('Failed ');
       }
 });

If you don't want to use Url.Action, you can also do not use Ajax, using the Form Tag Helper to submit data is the same. You can check the details in this official document.

  • Related