bb2
bb2

Reputation: 97

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);
}

[httpost]
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!

Upvotes: 2

Views: 162

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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.

Upvotes: 3

Related Questions