0

I have a problem, I want to add a new row into my database using C# MVC AJAX and it doesn't work. I can see the value of the textbox as a parameter in the URL, but when I click on the submit button, it doesn't work and I don't know how to proceed. Can you please help me to solve this problem? Here's the codes :

My method in the Controller who contains the insert instruction:

public void AddCategorie(string cat)
{
    Category cate = new Category();
    cate.CategoryNom = cat;
    db.Categories.Add(cate);
    db.SaveChanges();
}

My code in the View who's showing the result :

@{
    ViewBag.Title = "Gestion des catégories";
}

<hgroup class="title">
    <h1>@ViewBag.Title</h1>
</hgroup>

<section class="contact">
    <form ng-model="AddCategorie()">
        <input type="text" name="name" placeholder="Nouvelle catégorie" /><br />
        <input type="submit" value="Ajouter" />
    </form>
    <input type="submit" value="Modifier" />
    <input type="submit" value="Supprimer" />
</section>

The code in the Index (maybe it can help) It's showing the main page of the application:

@{
    ViewBag.Title = "Home Page";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
<script src="http://bootswatch.com/spacelab/bootstrap.min.css"></script>

@*<script src="jquery.min.js"></script>
<script src="jssor.slider.mini.js"></script>
<script>
    jQuery(document).ready(function ($) {
        var options = { $AutoPlay: true };
        var jssor_slider1 = new $JssorSlider$('slider1_container', options);
    });
</script>*@

<style>
    .categories, .animes, .perso {
        color: #000;
        margin-left: 35px;
    }
</style>


<script>
    templateCategories = null;
    templateAnimes = null;
    templatePerso = null;

    $(function () {
        templateCategories = Handlebars.compile($('#CategoriesTemplate').html());
        templateAnimes = Handlebars.compile($('#AnimesTemplate').html());
        templatePerso = Handlebars.compile($('#PersoTemplate').html());

        $.getJSON("Animes/GetCategories", null, function (data) {
            var result = templateCategories(data);

            $('#CategoriesOutput').html(result);
        });
    });

    function GetAnimes(catID) {
        $.getJSON("Animes/GetAnimes", { categoryID: catID }, function (data) {
            var resAnimes = templateAnimes(data);

            $('#AnimesOutput').html(resAnimes);
            $('lstCat').html(resAnimes);
        });
    }

    function GetPersonnages(aniID) {
        $.getJSON("Animes/GetPersonnages", { animeID: aniID }, function (data) {
            var resPerso = templatePerso(data);

            $('#PersoOutput').html(resPerso);
            $('#lstAni').html(resPerso);
        });
    }

    function AddCategorie(categorie) {
        $.getJSON("Animes/AddCategorie", { cat: categorie }, function (data) {
    });
}

</script>

<h2>Slideshow</h2>
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px; height: 300px;">
    <!-- Slides Container -->
    <div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; width: 600px; height: 300px;">
        <div><img src="../imgs/elfen1.jpg" /></div>
    </div>
</div>


<h3>Catégories</h3>

<div id="CategoriesOutput">

</div>

<h3>Animes</h3>

<div id="AnimesOutput">

</div>

<h3>Personnages</h3>

<div id="PersoOutput">

</div>

<script id="CategoriesTemplate" type="text/x-handlebars-template">
    {{#each}}
    <h3 class="categories" onclick="GetAnimes({{CategoryID}})">{{CategoryNom}}</h3>
    {{/each}}
</script>

<script id="AnimesTemplate" type="text/x-handlebars-template">
    {{#each}}
    <h3 class="animes" onclick="GetPersonnages({{AnimeID}})">{{AnimeNom}}</h3>
    {{/each}}
</script>

<script id="PersoTemplate" type="text/x-handlebars-template">
    {{#each}}
    <h3 class="perso">{{PersonnageNom}}</h3>
    {{/each}}
</script>
9
  • I don't see your AJAX call. Could you post it? Or maybe I'm missing something... Commented Jul 2, 2015 at 1:03
  • you mean something like : $.getJSON(......... Daniel? Commented Jul 2, 2015 at 1:05
  • It's looks like this for now : function AddCategorie(categorie) { $.getJSON("Animes/AddCategorie", { cat: categorie }, function (data) { }) I just don't know what to place between the braces Commented Jul 2, 2015 at 1:09
  • 1
    Yes exactly! I don't see a call that POSTs to ~/AddCategorie , is the data being passed to the method properly? Commented Jul 2, 2015 at 1:09
  • Please add that to original post Joel for anyone who won't look in the comments =) Also that is correct syntax, where/how are you calling your function AddCategorie()? Can you manually hit that function and see if it is passing data to your Controller? Commented Jul 2, 2015 at 1:30

2 Answers 2

2

First, you don't need this attribute on the form:

<form ng-model="AddCategorie()">

ng-model would only come into play if you were using Angular, which you don't seem to be. Also, AddCategorie currently has no explicit return value, which means its result is undefined. So, that wouldn't quite be what you wanted even if you were using Angular.


As for your problem, I believe the root of it is that you're running into this problem with the browser's form submission taking precedence over your JavaScript.

Since your form has no action or method specified, clicking the submit button is submitting the form with its default action and method. That's a GET back to the current URL. That's why you're seeing URL change to something like Animes/Index?name=category in the URL after submitting, but your AddCategorie action isn't being called.

To get this working, I would modify the form something like this:

<form id="add-categorie">
    <input type="text" id="nouvelle-categorie-nom" placeholder="Nouvelle catégorie" /><br />
    <input type="submit" value="Ajouter" />
</form>

Then, attach an event handler to monitor for the form's submit event:

$('#add-categorie').on('submit', function(evt) {
  // This is the key line to prevent the default browser behavior of
  //  sending a GET back to the current URL.
  evt.preventDefault();

  var data = {
    // Did I get my Francias correct?
    cat: $('#nouvelle-categorie-nom').val();
  };

  // This should be a POST, not a GET (ala $.getJSON).
  $.post('/Animes/AddCategorie', data);
});

I'd also suggest not even allowing GET for this, because it's not an idempotent operation:

[HttpPost]
public void AddCategorie(string cat) {
    db.Categories.Add(new Category { CategoryNom = cat });
    db.SaveChanges();
}  

There's a long list of both practical and theoretical reasons why you shouldn't use GET here instead of POST, but the one that will most immediately cause you trouble will be browser caching for GET requests.

Sign up to request clarification or add additional context in comments.

Comments

0

Doesn't look like you are posting based on the provided code. You should be able to set a debug marker in AddCategories and see if it is getting to that method. Something like:

$.postJSON("Animes/AddCategorie",{ cat: 1 }, function (data) {

});

http://www.make-awesome.com/2012/11/jquery-postjson-method-for-asp-net-mvc/
http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example
Angularjs $http.post, asp.net mvc controller gets null


BTW, if you are expecting AddCategorie to return a value, I would expect it to be a json value, not void. Otherwise, alert("error") will display, and not "helloWorld". Though, if Daniel has any comments on this, I would love to hear them.

Error: (Error)

public void AddCategorie(string cat)
        {
            Category category = new Category();
            category.CategoryNom = cat;

            //return Json(category, JsonRequestBehavior.AllowGet);
        }

jQuery.getJSON("Search/AddCategorie", { cat: '2' }, function (data) {
    alert("helloWorld");
}).error(function (data) {
    alert("error");
});

Not Error: (HelloWorld)

public JsonResult AddCategorie(string cat)
        {
            Category category = new Category();
            category.CategoryNom = cat;

            return Json(category, JsonRequestBehavior.AllowGet);
        }

jQuery.getJSON("Search/AddCategorie", { cat: '2' }, function (data) {
    alert("helloWorld");
}).error(function (data) {
    alert("error");
});

if you want to post without error to the void:

jQuery.post("Search/AddCategorie", { cat: '2' }, function (data) {
    alert("helloworld");
}).error(function (data) {
    alert("error");
});

3 Comments

How is this not useful?
While I agree debugging is a great idea, "try this" answers should be posted in comments and not as solutions, and $.postJSON does not exist as a function in the angular or jquery libraries, unless specifically created it will not function.
blame stackoverflow. I can't comment. .....then create it, just like you would create: $.ajax({ type: 'POST', url: '/form/', data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}), success: function(data) { alert('data: ' + data); }, contentType: "application/json", dataType: 'json' });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.