开发者

How to pass a System.String data to a strongly-typed view?

My idea is to pass a string data to a strongly-typed view as follows:

Controller:

 public ActionResult Confirmation()     
 {         
      string message = TempData["message"] as string;      
      if (message != null)
         return View(message);//it does not work     
      else  
         return RedirectToAction("Index");    
 } 

View:

@Model System.String
@{
开发者_如何学Go    ViewBag.Title = "Confirmation";
}
<h2>
    Confirmation</h2>
@Model

However, it does not work.

How to make it work?

EDIT 1

I can make it work by downcast message to object as follows:

return View((object)message);


I think MVC is getting slightly confused here. It won't work because it will try to return a ViewName of whatever you have in Message at the time.

There are at least three overloads you can use:

return View(string viewName);

// or..
return View(object model); // this is the one you're trying to use

// or..
return View(string viewName, object model);

MVC in your case is trying to do the first one but is using your variable Message as the view name. Try changing it to this to force it to use the correct overload:

return View("Confirmation", message);

.. and see what happens then.

Edit: Didn't realise you were not using the Index action; updated the example, but the point remains the same.


Why dont you try a ViewBag property to pass the string to the view or create a ViewModel with a string property:

public class ConfimationModel
{
  public string Message{get;set;}
}

 public ActionResult Confirmation()     
 {         
      string message = TempData["message"] as string; 
      //Model Option
      var model = new ConfirmationModel();
      model.Message = message;     
      if (message != null)
         return View(model);     
      else  
         return RedirectToAction("Index"); 

      //ViewBag Option
      ViewBag.Message = message; 

      if (message != null)
         return View();     
      else  
         return RedirectToAction("Index");   
 } 

View:

@Model ConfimationModel
@{
    ViewBag.Title = "Confirmation";
}
<h2>@Model.Message</h2>

    OR

   <h2>@ViewBag.Message</h2>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜