开发者

How to return back a message after a submit

开发者 https://www.devze.com 2022-12-29 13:57 出处:网络
I have the following code which is not working as expected.I want to have a retrun from the controller and using alert display the value returned from the controller.

I have the following code which is not working as expected. I want to have a retrun from the controller and using alert display the value returned from the controller.

 $('#change').dialog({
            autoOpen: false,
            width: 380,
            buttons: {
                "Close": function() {
                    $(this).dialog("close");
                },
                "Accept": function() {
                    var test = $("#ChangePasswordForm").submit();
                    alert(test);
                }
            }
        });

In my controller I want to return a string

  [AcceptVerbs(HttpVerbs.Post)]
    public string ChangePassword(string Nam开发者_C百科e)
    {
        var msg = "Cool!";
if (name != null)


return msg;
                }

How can I do that?


Your controller needs to return a type that derives from an ActionResult.

If you want to display a simple confirmation message you can add it to the ViewData bag like this:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ChangePassword(string name)
    {
        if (!string.IsNullOrEmpty(name))
        {
            ViewData["msg"] = "Cool";
        }
        return View();
    }

Then, in your view, check for the presence of the value, and display it if it's there:

<% if(ViewData["msg"] != null) { %>
    <script type="text/javascript">alert('<%= ViewData["msg"].ToString() %>')</script>
<%} %>


First of all, im assuming you are using an ajax form for this. I also assume you have a or something for putting your text into. All you have to do is set the UpdateTargetId to point at the id of the element you want to update with the text

<%using (Ajax.Form("ChangePasswordForm", new AjaxOptions { UpdateTargetId = "result" })) %>

.

[HttpPost]
public ContentResult ChangePassword(string s)
{
      var msg = "Cool!";
      if ( s != null ? return Content(msg, "text/plain") : return Content("An error has occured", "text/plain") );
}


  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult ChangePassword(string Name)
  {
        var msg = "Cool!";
        if (name != null)
        {       
            return Content(msg, "text/plain");
        }
        else
        {
            return Content("Error...", "text/plain");
        }
   }


Don't submit the form as that will perform a postback and cause the dialog to be removed.

Instead perform an AJAX post to the Controller Action and return a JsonResult containing the data.

Hook into the success callback from the Ajax request, and call alert passing the data from the Json object.

You'll probably wan't to use a loading mask after clicking submit so the user knows something is going on.

0

精彩评论

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