3

I have a Personal GPA Tracker project to work on, and i'm trying to get a modal to pop up from my CRUD functions. I have it semi working wherein it returns a partial view, but not in modal form. I think my logic is messed up somewhere or i'm not using JQuery and Ajax correctly or something. Any help would be appreciated.

Here is what I have so far.

Home Controller

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Course course = _db.Courses.Find(id);
    if (course == null)
    {
       return HttpNotFound();
    }
    return PartialView("_Edit", course);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Course course)
{
    if (ModelState.IsValid)
    {
        _db.Entry(course).State = EntityState.Modified;
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View("Index");
}

CourseList Partial called from Index

 <td>
       @Html.ActionLink("Edit", "Edit", new { id = item.Id, @data_toggle="modal", @data_target="editCourseModal" } ) |
       @Html.ActionLink("Details", "Details", new { id = item.Id }) |
       @Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>

Script inside of the CourseList

<script type="text/javascript">
  $(function() {
    $('editCourseModal').on("click", function(e) {
      $('formEditCourse').load(this.href, function() {
        $('editCourseModal').modal({
          keyboard: true
        }, 'show');
      })
    })
    $("#editBtn").on("click", function() {
      $("#formEditCourse").submit();
    });
    $("#formEditCourse").on("submit", function(event) {
      var $form = $(this);
      var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
      };

    });
  });
</script>

Edit Partial

@model Project3.Models.Course
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div id="mainContent" class="modal-content col-sm-12">
      <div id="myModalContent"></div>
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Edit Course</h4>
      </div>

      @using (Html.BeginForm()) { @Html.AntiForgeryToken()

      <div class="modal-body">
        <div class="form-horizontal">

          @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.Id)

          <div class="form-group">
            @Html.LabelFor(model => model.courseCode, htmlAttributes: new { @class = "control-label col-md-3" })
            <div class="col-md-9">
              @Html.EditorFor(model => model.courseCode, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.courseCode, "", new { @class = "text-danger" })
            </div>
          </div>

          <div class="form-group">
            @Html.LabelFor(model => model.courseName, htmlAttributes: new { @class = "control-label col-md-3" })
            <div class="col-md-9">
              @Html.EditorFor(model => model.courseName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.courseName, "", new { @class = "text-danger" })
            </div>
          </div>

          <div class="form-group">
            @Html.LabelFor(model => model.courseHours, htmlAttributes: new { @class = "control-label col-md-3" })
            <div class="col-md-9">
              @Html.EditorFor(model => model.courseHours, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.courseHours, "", new { @class = "text-danger" })
            </div>
          </div>
          <div class="form-group">
            @Html.LabelFor(model => model.courseLetterGrade, htmlAttributes: new { @class = "control-label col-md-3" })
            <div class="col-md-9">
              @Html.EditorFor(model => model.courseLetterGrade, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.courseLetterGrade, "", new { @class = "text-danger" })
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Cancel</button>
        <input class="btn btn-primary" type="submit" value="Save" />
      </div>
    </div>
  </div>
</div>
}
When I click the CRUD operations, it just pulls up a partial view, I have the create modal working, and I tried to model all CRUD operations after that, but cannot get it to work for pulling dynamic data into the fields.

Again, any help would be greatly appreciated.

  • Does the form POST reach the controller/action ? `$("#editBtn").` is not on the form..? – Searching Nov 29 '16 at 02:39
  • @Searching I've added it to the `Edit` form ``, but no difference. It's still only pulling the partial _Edit view and no modal. –  Nov 29 '16 at 03:34
  • Give that the edit page with the form loads, when you click on submit, button, you should have network activity (check dev tools on your browser) and also a break point on your action.. – Searching Nov 29 '16 at 03:39
  • So you click on EDIT link, the Modal dialog shows and then the _Edit page doesn't even load or it loads with no data in the input fields ? – Searching Nov 29 '16 at 03:57
  • @Searching I can't even get the modal to pop up. It goes directly to the _Edit partial with the correct data in the fields. My problem is getting the modal to pop up once I click any of the CRUD functions, except I got the create modal to work. –  Nov 29 '16 at 03:59

1 Answers1

4

That last comment helped..

script: was not binding with the link properly..

$(function () {
    $('.editCourseModal').on("click", function (e) {
        e.preventDefault();
        //perform the url load  then
            $('#myModal').modal({
                keyboard : true
            }, 'show');
        return false;
    })
})

html : tags were not in the html attributes previously..

@Html.ActionLink("Edit", "Edit", new { id = item.Id}, new { @class="editCourseModal", @data_target="editCourseModal"}) 

myModal div (tag only) ,should be on the same page as the link so when you click it pops up. But in your code you have it in the Edit page. Also I couldn't find formEditCourse. Not sure how these linked. I'm not familiar with the load used to load the edit page. If it works and you are comfortable then you should continue with it..


Other/My approach. This way I can load all the partial pages in this modal. The page rendered/replaced will change based on the link.

In your CourseList or index page

<div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div id="mainContent" class="modal-content col-sm-12">



        </div> 
    </div>
</div>

Script : when the user clicks on the #editCourseModal link we will prevent the default action and replace the #mainContnet div with the _Edit partial page loaded via ajax request. Then we trigger the show modal.

$(function () {
    $('.editCourseModal').on("click", function (e) {
        e.preventDefault();
        //replace the get with this.href to load the edit page
        $.get('https://developer.mozilla.org/en-US/docs/Web', function (data) {
            //replace the content returned
            $("#mainContent").html(data);
        });
        //show the modal
        $('#myModal').modal({
            keyboard : true,
        }, 'show');
        return false;
    })

})

Edit page : this will still be same as you have it but will only contain the header, body and footer. The Form part you have will stay the same...

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Edit Course</h4>
</div>

<div class="modal-body">
    //YOUR EXISTING FORM HERE
</div>

<div class="modal-footer">
    <button class="btn" data-dismiss="modal">Cancel</button>
    <input class="btn btn-primary" type="submit" value="Save" />
</div>

Check this link for form validation issues. Let us know how it goes.

Community
  • 1
  • 1
Searching
  • 2,269
  • 1
  • 17
  • 28
  • thank you so much, in the code snippet you put for the `CourseList/Index` am I supposed to put anything inside the `maincontent` div? Or do I leave it blank? I'm confused, because for my create form that has the modal working, I have that snippet inside my actual `Create` view. –  Nov 29 '16 at 12:14
  • @JDubbleU, updated answer with bit more info. do let me know if in doubt – Searching Nov 29 '16 at 19:25
  • Ok! Thank you for getting me this far! I managed to finally get the modal to pop up with your guidance, but it's only working for the first item. If I click edit on any other record, it reverts back to the ugly partial view (no modal). How and why is this happening? –  Nov 29 '16 at 23:22
  • @JDubbleU Great. I think a small change to the `ActionLink`. instead of `@id=..editCourseModal` use `@class=editCourseModal`. I've updated the script aswell with that change. `id` should be unique...That's probably the issue... – Searching Nov 29 '16 at 23:49
  • I was literally just about to say that! Haha thank you so much! –  Nov 30 '16 at 00:01