Saving changes to the DB MVC












0















I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.



Model:



 public class Hello
{
List<string> Ids { get; set; }

List<string> Dates { get; set; }
}


Controller:



   [HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{

using (db = new DB())
{

rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();

if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}

}

}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}


View:



  <td><input class="id" type="checkbox" id=@item.ID /></td>
<td>@Html.DisplayFor(x => @item.ID)</td>
<td><input class="date" id=date@item.ID type="text" value='@item.Date'/></td>

$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};


Any help would be appreciated!










share|improve this question





























    0















    I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.



    Model:



     public class Hello
    {
    List<string> Ids { get; set; }

    List<string> Dates { get; set; }
    }


    Controller:



       [HttpPost]
    public ActionResult Process(string ids, string dates)
    {
    Hello model = new Hello();
    if (ModelState.IsValid)
    {

    using (db = new DB())
    {

    rp = new RequestProcess();
    //var c = rp.getHello(model, dates);
    var c = rp.getStuff();

    if (c != null)
    {
    foreach (var i in c)
    {
    if (i != null)
    {
    ids = i.ID;
    dates = i.Date.ToString();
    }
    db.SaveChanges();
    }

    }

    }
    ViewBag.Message = "Success";
    return View(model);
    }
    else
    {
    ViewBag.Message = "Failed";
    return View(model);
    }
    }


    View:



      <td><input class="id" type="checkbox" id=@item.ID /></td>
    <td>@Html.DisplayFor(x => @item.ID)</td>
    <td><input class="date" id=date@item.ID type="text" value='@item.Date'/></td>

    $(document).ready(function () {
    var ids = "";
    var dates = "";
    $("#btnSubmit").bind("click", function () {
    createUpdateArrays();
    var url = "/Sample/Process";
    $.ajax({
    type: "POST",
    url: url,
    data: { ids: ids, dates: dates },
    contentType: 'application/json; charset=utf-8',
    success: function (success) {
    if (success === true) {
    alert("HERE WE ARE");
    }
    else {
    alert("eror");
    }
    }
    });
    ids = "";
    dates = "";
    });
    function createUpdateArrays() {
    var i = 0;
    $('input.remedy-id:checkbox').each(function () {
    if ($(this).is(':checked')) {
    var rid = $(this).attr("id");
    $('.planned-date').each(function () {
    var did = $(this).attr("id");
    if (did === rid) {
    var date = $(this).val();
    ids += rid + ",";
    dates += date + ",";
    }
    });
    };
    });
    };


    Any help would be appreciated!










    share|improve this question



























      0












      0








      0








      I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.



      Model:



       public class Hello
      {
      List<string> Ids { get; set; }

      List<string> Dates { get; set; }
      }


      Controller:



         [HttpPost]
      public ActionResult Process(string ids, string dates)
      {
      Hello model = new Hello();
      if (ModelState.IsValid)
      {

      using (db = new DB())
      {

      rp = new RequestProcess();
      //var c = rp.getHello(model, dates);
      var c = rp.getStuff();

      if (c != null)
      {
      foreach (var i in c)
      {
      if (i != null)
      {
      ids = i.ID;
      dates = i.Date.ToString();
      }
      db.SaveChanges();
      }

      }

      }
      ViewBag.Message = "Success";
      return View(model);
      }
      else
      {
      ViewBag.Message = "Failed";
      return View(model);
      }
      }


      View:



        <td><input class="id" type="checkbox" id=@item.ID /></td>
      <td>@Html.DisplayFor(x => @item.ID)</td>
      <td><input class="date" id=date@item.ID type="text" value='@item.Date'/></td>

      $(document).ready(function () {
      var ids = "";
      var dates = "";
      $("#btnSubmit").bind("click", function () {
      createUpdateArrays();
      var url = "/Sample/Process";
      $.ajax({
      type: "POST",
      url: url,
      data: { ids: ids, dates: dates },
      contentType: 'application/json; charset=utf-8',
      success: function (success) {
      if (success === true) {
      alert("HERE WE ARE");
      }
      else {
      alert("eror");
      }
      }
      });
      ids = "";
      dates = "";
      });
      function createUpdateArrays() {
      var i = 0;
      $('input.remedy-id:checkbox').each(function () {
      if ($(this).is(':checked')) {
      var rid = $(this).attr("id");
      $('.planned-date').each(function () {
      var did = $(this).attr("id");
      if (did === rid) {
      var date = $(this).val();
      ids += rid + ",";
      dates += date + ",";
      }
      });
      };
      });
      };


      Any help would be appreciated!










      share|improve this question
















      I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.



      Model:



       public class Hello
      {
      List<string> Ids { get; set; }

      List<string> Dates { get; set; }
      }


      Controller:



         [HttpPost]
      public ActionResult Process(string ids, string dates)
      {
      Hello model = new Hello();
      if (ModelState.IsValid)
      {

      using (db = new DB())
      {

      rp = new RequestProcess();
      //var c = rp.getHello(model, dates);
      var c = rp.getStuff();

      if (c != null)
      {
      foreach (var i in c)
      {
      if (i != null)
      {
      ids = i.ID;
      dates = i.Date.ToString();
      }
      db.SaveChanges();
      }

      }

      }
      ViewBag.Message = "Success";
      return View(model);
      }
      else
      {
      ViewBag.Message = "Failed";
      return View(model);
      }
      }


      View:



        <td><input class="id" type="checkbox" id=@item.ID /></td>
      <td>@Html.DisplayFor(x => @item.ID)</td>
      <td><input class="date" id=date@item.ID type="text" value='@item.Date'/></td>

      $(document).ready(function () {
      var ids = "";
      var dates = "";
      $("#btnSubmit").bind("click", function () {
      createUpdateArrays();
      var url = "/Sample/Process";
      $.ajax({
      type: "POST",
      url: url,
      data: { ids: ids, dates: dates },
      contentType: 'application/json; charset=utf-8',
      success: function (success) {
      if (success === true) {
      alert("HERE WE ARE");
      }
      else {
      alert("eror");
      }
      }
      });
      ids = "";
      dates = "";
      });
      function createUpdateArrays() {
      var i = 0;
      $('input.remedy-id:checkbox').each(function () {
      if ($(this).is(':checked')) {
      var rid = $(this).attr("id");
      $('.planned-date').each(function () {
      var did = $(this).attr("id");
      if (did === rid) {
      var date = $(this).val();
      ids += rid + ",";
      dates += date + ",";
      }
      });
      };
      });
      };


      Any help would be appreciated!







      javascript jquery ajax asp.net-mvc






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 27 '18 at 19:31







      caitlinp

















      asked Nov 26 '18 at 22:10









      caitlinpcaitlinp

      677




      677
























          2 Answers
          2






          active

          oldest

          votes


















          0














          I think you need contentType: 'application/json' in your $.ajax({});



          $.ajax({
          type: "POST",
          url: url,
          data: JSON.stringify(list),
          contentType: 'application/json'
          });


          Also, try adding [FromBody]Hello model in your controller action.






          share|improve this answer































            0














            There are several issues in your code:



            1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.



            2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.



            Therefore, you should use AJAX setup as provided below:



            $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(list),
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
            $('#targetElement').html(result);
            },
            error: function (xhr, status, err) {
            // error handling
            }
            });


            Controller Action



            [HttpPost]
            public ActionResult Process(Hello model)
            {
            if (ModelState.IsValid)
            {
            using (db = new DB())
            {
            // save data
            }
            ViewBag.Message = "Success";
            return PartialView("_PartialViewName", model);
            }
            else
            {
            ViewBag.Message = "Failed";
            return PartialView("_PartialViewName", model);
            }
            }


            Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).






            share|improve this answer
























            • This doesn't seem to work @Tetsuya

              – caitlinp
              Nov 27 '18 at 15:29











            • Posted the code edits, still stuck on the same issue..

              – caitlinp
              Nov 27 '18 at 19:32











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53489896%2fsaving-changes-to-the-db-mvc%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I think you need contentType: 'application/json' in your $.ajax({});



            $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(list),
            contentType: 'application/json'
            });


            Also, try adding [FromBody]Hello model in your controller action.






            share|improve this answer




























              0














              I think you need contentType: 'application/json' in your $.ajax({});



              $.ajax({
              type: "POST",
              url: url,
              data: JSON.stringify(list),
              contentType: 'application/json'
              });


              Also, try adding [FromBody]Hello model in your controller action.






              share|improve this answer


























                0












                0








                0







                I think you need contentType: 'application/json' in your $.ajax({});



                $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(list),
                contentType: 'application/json'
                });


                Also, try adding [FromBody]Hello model in your controller action.






                share|improve this answer













                I think you need contentType: 'application/json' in your $.ajax({});



                $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(list),
                contentType: 'application/json'
                });


                Also, try adding [FromBody]Hello model in your controller action.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 26 '18 at 22:18









                Hubert JaremaHubert Jarema

                6,37372866




                6,37372866

























                    0














                    There are several issues in your code:



                    1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.



                    2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.



                    Therefore, you should use AJAX setup as provided below:



                    $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(list),
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                    $('#targetElement').html(result);
                    },
                    error: function (xhr, status, err) {
                    // error handling
                    }
                    });


                    Controller Action



                    [HttpPost]
                    public ActionResult Process(Hello model)
                    {
                    if (ModelState.IsValid)
                    {
                    using (db = new DB())
                    {
                    // save data
                    }
                    ViewBag.Message = "Success";
                    return PartialView("_PartialViewName", model);
                    }
                    else
                    {
                    ViewBag.Message = "Failed";
                    return PartialView("_PartialViewName", model);
                    }
                    }


                    Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).






                    share|improve this answer
























                    • This doesn't seem to work @Tetsuya

                      – caitlinp
                      Nov 27 '18 at 15:29











                    • Posted the code edits, still stuck on the same issue..

                      – caitlinp
                      Nov 27 '18 at 19:32
















                    0














                    There are several issues in your code:



                    1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.



                    2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.



                    Therefore, you should use AJAX setup as provided below:



                    $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(list),
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                    $('#targetElement').html(result);
                    },
                    error: function (xhr, status, err) {
                    // error handling
                    }
                    });


                    Controller Action



                    [HttpPost]
                    public ActionResult Process(Hello model)
                    {
                    if (ModelState.IsValid)
                    {
                    using (db = new DB())
                    {
                    // save data
                    }
                    ViewBag.Message = "Success";
                    return PartialView("_PartialViewName", model);
                    }
                    else
                    {
                    ViewBag.Message = "Failed";
                    return PartialView("_PartialViewName", model);
                    }
                    }


                    Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).






                    share|improve this answer
























                    • This doesn't seem to work @Tetsuya

                      – caitlinp
                      Nov 27 '18 at 15:29











                    • Posted the code edits, still stuck on the same issue..

                      – caitlinp
                      Nov 27 '18 at 19:32














                    0












                    0








                    0







                    There are several issues in your code:



                    1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.



                    2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.



                    Therefore, you should use AJAX setup as provided below:



                    $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(list),
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                    $('#targetElement').html(result);
                    },
                    error: function (xhr, status, err) {
                    // error handling
                    }
                    });


                    Controller Action



                    [HttpPost]
                    public ActionResult Process(Hello model)
                    {
                    if (ModelState.IsValid)
                    {
                    using (db = new DB())
                    {
                    // save data
                    }
                    ViewBag.Message = "Success";
                    return PartialView("_PartialViewName", model);
                    }
                    else
                    {
                    ViewBag.Message = "Failed";
                    return PartialView("_PartialViewName", model);
                    }
                    }


                    Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).






                    share|improve this answer













                    There are several issues in your code:



                    1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.



                    2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.



                    Therefore, you should use AJAX setup as provided below:



                    $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(list),
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                    $('#targetElement').html(result);
                    },
                    error: function (xhr, status, err) {
                    // error handling
                    }
                    });


                    Controller Action



                    [HttpPost]
                    public ActionResult Process(Hello model)
                    {
                    if (ModelState.IsValid)
                    {
                    using (db = new DB())
                    {
                    // save data
                    }
                    ViewBag.Message = "Success";
                    return PartialView("_PartialViewName", model);
                    }
                    else
                    {
                    ViewBag.Message = "Failed";
                    return PartialView("_PartialViewName", model);
                    }
                    }


                    Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 27 '18 at 1:12









                    Tetsuya YamamotoTetsuya Yamamoto

                    16.2k42240




                    16.2k42240













                    • This doesn't seem to work @Tetsuya

                      – caitlinp
                      Nov 27 '18 at 15:29











                    • Posted the code edits, still stuck on the same issue..

                      – caitlinp
                      Nov 27 '18 at 19:32



















                    • This doesn't seem to work @Tetsuya

                      – caitlinp
                      Nov 27 '18 at 15:29











                    • Posted the code edits, still stuck on the same issue..

                      – caitlinp
                      Nov 27 '18 at 19:32

















                    This doesn't seem to work @Tetsuya

                    – caitlinp
                    Nov 27 '18 at 15:29





                    This doesn't seem to work @Tetsuya

                    – caitlinp
                    Nov 27 '18 at 15:29













                    Posted the code edits, still stuck on the same issue..

                    – caitlinp
                    Nov 27 '18 at 19:32





                    Posted the code edits, still stuck on the same issue..

                    – caitlinp
                    Nov 27 '18 at 19:32


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53489896%2fsaving-changes-to-the-db-mvc%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Lallio

                    Unable to find Lightning Node

                    Futebolista