开发者

How to handle $.ajax

开发者 https://www.devze.com 2023-02-15 10:43 出处:网络
I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to$.ajax.

I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to $.ajax.

Is possible with $.ajax otherwise how can I?

Becase following code does not redirect.

[code]

   [HttpPost]
    public ActionResult Save(RecipeViewModel postdata)
    {
        Recipe recipe = postdata.GetRecipe(_user.UserID);

        int recipeid = _service.AddRecipe(recipe, null, true);

        foreach (Ingredient ing in recipe.Ingredients)
        {
            ing.RecipeID = recipeid;
            _service.AddIngredient(ing, null, false);
        }

        if (!postdata.Comment.IsEmpty())
        {
            Comment comment = new Comment();
            comment.fldComment = postdata.Comment;
            comment.RecipeID = recipeid;
            comment.UserID = _user.UserID;
            comment.EnteredByName = _user.Names;
            comment.EnteredOn = DateTime.Now.ToString();
            _service.AddComment(comment, null, false);
        }

        _service.SubmitChanges();

        return RedirectToAction("View", "Recipe", new { i开发者_开发知识库d = recipeid });
    }

u<script type="text/javascript">
$("#Save").click(function () {
    var ingredients = $("#ingredients tr.ingredientdata").map(function (element, index) {
        return {
            ingredientName: $("td.ingredient", this).text(),
            units: $("td.units", this).text(),
            measure: $("td.measure", this).text()
        };
    }).toArray();

    var json = {
        RecipeTitle: $("#recipetitle").val(),
        CategoryID: $("#category").val(),
        PrepTime: $("#prepTime").val(),
        PrepTimePeriod: $("#lstPrepTime").val(),
        CookTime: $("#cookTime").val(),
        CookTimePeriod: $("#lstCookTime").val(),
        Rating: $("#rating").val(),
        Method: $("#method").val(),
        Comment: $("#comment").val(),
        AccessLevel: $("#accessLevel").val(),
        Ingredients: ingredients
    };

    $.ajax({
        url: "/Recipe/Save",
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(json),
        contentType: "application/json; charset=utf-8",
        success: function () {
            //alert("DONE!!");
        }
    });
});

[/code] Malcolm


You need to send back the Url and redirect it from the client script.

       success: function (urlData) {
           window.location.href = urlData ;
           return false;
       } 

or you may show an error message based on the response received.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号