Click here to Skip to main content
15,068,645 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 });
}
   
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?
F-ES Sitecore 20-Aug-20 11:25am
   
It will go to HttpGet when you issue a "GET" request which happens when you click a link, put the url in the address bar or do a code-based redirect to the action. It goes to HttpPost when you submit a form with method=POST and has the action in the "action" attribute of the form (or use ajax to do a post to the action).
gcogco10 20-Aug-20 11:40am
   
On the client side if you look at it, i am calling post there. Can you give me an example of this to the ActionResult side. The issue is there way i see it hence its not passing to [HttpPost]
F-ES Sitecore 20-Aug-20 11:47am
   
You're probably just getting confused about what your code is actually doing as it is doing so many things. You have a form that does a POST, a link that does a GET and javascript that does a POST...so three ways of instigating the action, but which one is actually being done? The form will only post if you click a submit button, the ajax will only post if you call the js function, and the link will GET when you click it. If you click the link to run the ajax code the link is still clicked so it still goes on to GET. You have to stop that by making the onclick return false.
gcogco10 20-Aug-20 12:03pm
   
I get your point, reason why i am doing click be true, that link opens up popup modal that i need to pass the data back to my database column, I dont know if sounds or make sense.
F-ES Sitecore 20-Aug-20 12:20pm
   
Yes, but having code in the onclick attribute doesn't stop the link navigation happening, so your modal shows then the browser instantly navigates away from the page, that's why you need it to return false.
gcogco10 20-Aug-20 12:27pm
   
i have a return false, now the form does not do nothing. not what i want there, help me there a second
F-ES Sitecore 20-Aug-20 12:55pm
   
It should show your modal, if that is properly configured, you don't show the mark-up for it, and you need to make sure the modal calls your "createCourses" function when it is submitted, or when the "Save" button in the modal is clicked. As createCourses uses the createCourseForm form to get its submission data from you need to make sure your "exampleModal" is inside the form you've created with BeginForm and has the relevant fields that the eNtsaRegCourses model needs.
F-ES Sitecore 20-Aug-20 13:18pm
   
I've updated my solution with a skeleton version of what you're probably trying to achieve
gcogco10 20-Aug-20 13:20pm
   
F-ES mind sharing that, im keen mate
F-ES Sitecore 20-Aug-20 13:51pm
   
Look at the solution I've already posted, I've added the code to the bottom of it.
gcogco10 20-Aug-20 14:39pm
   
Well i have used the example shared, it still does not hit the post on controller, only gets to [HttpGet].

@using(Html.BeginForm("CoursesRegistration", "Home", FormMethod.Post, new { id="saveData", @class="form-horizontal"})) { 
                            
                                
                                    
                                        
                                            <h5 class="modal-title" id="exampleModalLabel">Start New Course</h5>
                                            
                                                <span>×</span>
                                            
                                        
                                        
                                            CourseName
                                            
                                                @Html.EditorFor(model => model.CourseName, new { htmlAttributes = new { @class = "form-control", autofocus = "autofocus", placeholder = "CourseName" } })

                                            
                                        
                                        
                                            Content Licence
                                            
                                            
                                            
                                        
                                       
                                        
                                            Cancel
                                            <a href="@Url.Action(" class="btn btn-large btn-success">Create Courses</a>
                                            
                                                $("#exampleModal.btn-success").click(function () {
                                                    saveData();
                                                });

                                                function saveData() {
                                                    $.ajax({
                                                        url: "/Home/CoursesRegistration",
                                                        data: $('#coursesRegistration').serialize(),
                                                        type: 'post',
                                                        success: function (data) {
                                                            if (data.Success) {
                                                                $("#exampleModal").modal('hide');
                                                            } else {

                                                            }

                                                        },
                                                        error: function (xhr, status) {

                                                        }
                                                       
                                                    });
                                                    return false;
                                                }
F-ES Sitecore 20-Aug-20 15:26pm
   
There is a malformed <a> link in your code so it's hard to tell if it is just following the link when you click it as you seem to be setting the href to your action. Look at my example, the href is just a token "#" so it looks and acts like a link, the onclick then summons the modal.
gcogco10 20-Aug-20 20:00pm
   
F-ES Site had a work around, as a way to follow the skeleton. Some reason when i debug it only hits the HttpGet not HttPost method. Im still trying to understand the reason behind it. Actually currently the code looks exact the same, but the problem is on Httpost method is not getting in there at all.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



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