json success and fail response in MVC

☆樱花仙子☆ 提交于 2020-02-06 07:36:13

问题


I'm practicing Ajax! I have a simple contact form and this is my actions :

public ActionResult Contact()
        {
            return View("Contact");
        }

        [HttpPost]
        public ActionResult Contact(ContactViewModel contactViewModel)
        {
            if (ModelState.IsValid)
            {
                var contact = contactViewModel.ConvertToContactModel(); 
                _contactRepository.Add(contact);
                _contactRepository.Save();
                return Json(new { msg = "Your contact Sent, I'll response soon." });
            }
            return Json("Sorry! Somthing went wrong, try again or contact again");
        }

and this is my View :

@model Blog.Web.UI.ViewModels.ContactViewModel 
@{
    ViewBag.Title = "Contact";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div id="Contact">
    @using (Ajax.BeginForm("Contact", "Home", new AjaxOptions() { OnSuccess = "Success" }))
    {

        <div>
            @Html.LabelFor(c => c.Name)
            @Html.TextBoxFor(c => c.Name)
        </div>

        <div>
            @Html.LabelFor(c => c.Email)
            @Html.TextBoxFor(c => c.Email)
            @Html.ValidationMessageFor(c => c.Email)
        </div>

        <div>
            @Html.LabelFor(c => c.Subject)
            @Html.TextBoxFor(c => c.Subject)
        </div>

        <div>
            @Html.LabelFor(c => c.Body)
            @Html.TextAreaFor(c => c.Body)
            @Html.ValidationMessageFor(c => c.Body)
        </div>
        <input type="submit" value="Send" />
    }
</div>

<script type="text/javascript">
    function Success(context) {
        if (context[0]) {
            $("#Contact").empty().html(context[1]);
        }
    }
</script>

Now I wanna to show the user success or failing of contact made , what's the problem of my code that doesn't work?? it is so interesting that my validation doesn't work in this case! please help me about this , thanks


回答1:


Contrary to Slicksim, we usually have a JSON return class defined in our application models that contains a boolean variable Success. We can then use this to have the Javascript determine if the request was successful or not.

public class JsonResponseModel(){
   public bool Success {get;set;}

   public string Message {get;set;}
}

public ActionResult Contact()
        {
            return View("Contact");
        }

        [HttpPost]
        public ActionResult Contact(ContactViewModel contactViewModel)
        {
            if (ModelState.IsValid)
            {
                var contact = contactViewModel.ConvertToContactModel(); 
                _contactRepository.Add(contact);
                _contactRepository.Save();
                return Json(new JsonResponseModel{ Success = true, Messsage = "Your contact Sent, I'll response soon." });
            }
            return Json(new JsonResponseModel{Success = false, Message = "Sorry! Somthing went wrong, try again or contact again"});
        }

<script type="text/javascript">
    function Success(response) {
        if (response.Success) {
            $("#Contact").empty().html(response.Message);
        }
        else{
           alert(response.Message);
        }
    }
</script>

I suppose this is the route that we went instead of modifying the server headers because you may want to do something different if the validation failed on a AJAX call rather than an actual server error (HTTP Status COde 500/404/etc)




回答2:


if you want an error response so be sent, then you should set the ResponseCode of the Response object to a suitable http error code, such as 400 for bad request.

You will then need to provide an error handler in the ajax.beginform to display the content you want. If you don't, it will return a responsecode of 200 and that is treat that everything is hunky dory, so your error handler won't be triggered



来源:https://stackoverflow.com/questions/15880285/json-success-and-fail-response-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!