سؤال

This is my Controller :

    public JsonResult Success() { return Json(new { Success = true, Message = "Data Added Succefully" }); }
    public JsonResult Error(string message) { return Json(new { Success = false, Message = message }); }

    [HttpPost]
    public JsonResult CreateAjax(TAUX taux)
    {
        if (ModelState.IsValid)
        {
            try
            {
                foreach (short i in taux.SelectItems)
                {
                    taux.CAT_ID = i;
                    db.TAUX.Add(taux);
                    db.SaveChanges();

                }
                return Success();
            }
            catch (Exception err)
            {
                return Error(err.Message);
            }
        }

        ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE", taux.CAT_ID);
        ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE", taux.C_GARANT);

        return Error("The server wasn't able to do something right now.");
    }

This is My PartialView CreateAjax:

@model pfebs0.Models.TAUX
....
@using (Html.BeginForm("CreateAjax", "Taux", FormMethod.Post, new { id = "form" }))
{...}

And this is my View Index :

@model IEnumerable<pfebs0.Models.TAUX>
...
     <script>
         $.ajax({
             url: "/",
             method: "POST",
             data: getMyData(),

             success: function (json) {
                 if (json.Success) {
                     alert("Wow, everything was fine!");
                 } else {
                     alert(json.Message);
                 }
             },

             // This will be trigered whenever your ajax call fails (broken ISP link, etc).
             error: function () {
                 alert("Something went wrong. Maybe the server is offline?");
             }
         });

</script> 
...
       @Html.ActionLink("Ajouter", "Create", "Taux",
                new { id = "btnAdd", @class="btn btn-default"})
</p>
...
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
    $(function () {

        $.ajaxSetup({ cache: false });

        $('#btnAdd').click(function () {
            $('.modal-dialog').load(this.href, function () {
                $('#modalDiv').modal({
                    backdrop: 'static',
                    keyboard: true
                }, 'show');
            });
            return false;
        });
    });
....
 </script> }

What I'm trying to do here is to show success alert after Insertionn but after Insertion I'm redirected to new Page Localhost/Taux/ajaxCreate where It show me this message {"Success":true,"Message":"Data Added Succefully"} instead of showing PopUp with success message in Index Page. What's wrong here ?

هل كانت مفيدة؟

المحلول

You should use

@using (Ajax.BeginForm(....))
{   }

with the appropiate parameters.

See How can I return a JSON result to a Ajax.BeginForm for details.

There might be some issues with the script as well. What are you trying to do with:

<script>
     $.ajax({
         url: "/",
         method: "POST",
         data: getMyData(),

?

UPDATE Ok, this should work:

1) use your original

@using (Html.BeginForm

2) put the ajax call in a function:

<script type="text/javascript">
    function postData()
    {
         $.ajax({
             url: '@Url.Action("CreateAjax", "Taux")',
             method: "POST",
             data: $('#form').serialize(),

            ....
    }

3) change the type="submit" to type="button" at the submit button and add:

onclick="postData()"

attribute.

4) change ajax url:

url: '@Url.Action("CreateAjax", "Taux")',

5) add the change the getMyData function function

data: $('#form').serialize(), 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top