Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Team

I have method that stores value to the database on my asp.net mvc, some instance it does not stores that value. When i debug it does go through to all the methods. What could i be missing between my back end and front end(client side)?

What I have tried:

[HttpGet]
public ActionResult CoursesRegistration( eNtsaRegCourses model)
  {
      if(ModelState.IsValid)
      {
          try
          {
              cb.SaveChanges();
              return Json(new { success = true });
          }catch(Exception ex)
          {
              ModelState.AddModelError("", ex.Message);
          }
      }

      return PartialView("CoursesRegistration", model);
  }


  // saving changes here.
  static void SaveChanges(eNtsaCourses model)
  {

  }

// db-schema lists.
   public class eNtsaCourses
   {
       [Key]
       public Guid? Id { get; set; }
       public string Course { get; set; }
       public string Nickname { get; set; }
       public string Term { get; set; }
       public string EnrolledAs { get; set; }
       public bool Published { get; set; }

   }

@using (Html.BeginForm("CoursesRegistration", "Home", FormMethod.Post, new { id = "createCourseForm", @class = "form-horizontal" }))
                                       {
                                       <div class="modal-footer">
                                           <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                           <a href="@Url.Action("CoursesRegistration", "Home")" class="btn btn-large btn-success", onclick="$('#exampleModal').modal('show')">Create Courses</a>
                                           <script type="text/javascript">
                                               function createCourses() {
                                                   $.ajax({
                                                       url: "/Home/CoursesRegistration",
                                                       data: $('#createCourseForm').serialize(),
                                                       type: 'post',
                                                       success: function (data) {
                                                           if (data.Success) {
                                                               $("#exampleModal").modal('hide');
                                                           } else {

                                                           }

                                                       },
                                                       error: function (xhr, status) {

                                                       }

                                                   });
                                                   return false;
                                               }


                                           </script>

                                       </div>
                                       }
                                   </div>
Posted
Updated 20-Aug-20 3:10am

1 solution

<a href="@Url.Action("CoursesRegistration", "Home")" class="btn btn-large btn-success", onclick="$('#exampleModal').modal('show')">Create Courses</a>


Adding an "onclick" doesn't stop the link click action so your code is doing the modal('show') then immediately navigating to the href so going to your action. You need to stop the click happening so your modal is shown, do this by adding "return false"

<a href="@Url.Action("CoursesRegistration", "Home")" class="btn btn-large btn-success" onclick="$('#exampleModal').modal('show'); return false;">Create Courses</a>


You could also change the href to just

href="#"

as you don't want it to be a proper link, it is just there to fire your js to show the modal. Now change the action back to HttpPost

[HttpPost]
public ActionResult CoursesRegistration( eNtsaRegCourses model)


Updated

Here is a stripped down version of what you want to achieve

Modal

public class TestFormModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


View (TestForm.cshtml)

Razor
@model Models.TestFormModel

@using (Html.BeginForm("TestForm", "Home", FormMethod.Post, new { id = "testForm", @class = "form-horizontal" }))
{
    <p>
        <a href="#" onclick="$('#formModal').modal('show'); return false;">Show Modal</a>
    </p>
    <div class="modal" id="formModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        @Html.LabelFor(m => m.FirstName)
                        @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m.LastName)
                        @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
}

<script>
    $("#formModal .btn-primary").click(function () {
        saveForm();
    });

    function saveForm() {
        $.ajax({
            url: "/Home/TestForm",
            data: $('#testForm').serialize(),
            type: 'post',
            success: function (data) {
                if (data.Success) {
                    $("#formModal").modal('hide');
                } else {

                }

            },
            error: function (xhr, status) {

            }

        });
    }
</script>


Controller

C#
[HttpGet]
public ActionResult TestForm()
{
    return View();
}

[HttpPost]
public ActionResult TestForm(TestFormModel model)
{
    // save data here

    return Json(new { Success = true });
}
 
Share this answer
 
v3
Comments
gcogco10 20-Aug-20 9:23am    
[HttpPost] does not seem to work, i do need a link for other form to open href="@Url.Action("CoursesRegistration", "Home"). But with [HttpGet] no Server/Error Application. What am i missing that is my question?
F-ES Sitecore 20-Aug-20 10:59am    
Then you need both an HttpGet and HttpPost version of your action. The HttpGet will return a view with the form and the HttpPost will process the form once it is submitted.
gcogco10 20-Aug-20 11:02am    
[HttGet] ActionResult? [HttpPost] ActionResult also? is it allowed by mvc? to have this in one method or post will be on jquery side?
F-ES Sitecore 20-Aug-20 11:11am    
You can have both on the same action, but you normally need to split them into their own actions

[HttpGet]
public ActionResult CoursesRegistration()
{
    // return a View with the form in it
}

[HttpPost]
public ActionResult CoursesRegistration( eNtsaRegCourses model)
{
    // process the form
}
gcogco10 20-Aug-20 11:20am    
I have them both, when i debug it only stops on [HttpGet] only not pass to [HttpPost]. What could be the reason for this behavior?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900