开发者

how to send a message to a view ajax-like

I want to know about a pattern to do this. I have a controller with method1()

method1(){
 return View();

}
[httpost]
method1(string something){

  return View(object);
}

[httpos开发者_JAVA百科t]
method2(int? id){

  return redirectToaction("method1");
}

View:
<div>
beginform(){
   textfield
   submit button
}
</div>
<div>
if(viewbag.something != null){
   beginform("method2", "controller", new{id=number}){
     <span>@model.info</span>
     submit button
    }
}
</div>

and this displays a view this view has a form a text field and submit and this calls method1() but with the HTTPPOst and in the same view i display another form which will call method2() my question is how can i display a message in the view? like "user has been deleted" without having to create another view. Is there another way of doing this in asp mvc or do i have to include ajax?

I tried setting a viewBag inside method2, but since method2 redirectsaction to method1 it somehow does not stay, and it is not displayed in the view. Thanks!


You could use TempData which is preserved between a single redirect:

public ActionResult method1() 
{
    return View();
}

[HttpPost]
public ActionResult method1(string something)
{
    return View(something);
}

[HttpPost]
publicActionResult method2(int? id)
{
    TempData["message"] = "User has been deleted";
    return RedirectToAction("method1");
}

and in the view display the message:

<div>@TempData["message"]</div>

If there is no message in TempData it will simply display an empty div. You could further check if TempData["message"] != null in the view if you didn't want the empty div.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜