【问题标题】:The ViewBag content isn't being visualizedViewBag 内容没有被可视化
【发布时间】:2017-07-03 23:57:38
【问题描述】:

我是 ASP.NET MVC 网络开发的新手。 我正在尝试建立一个基本上可以访问可由用户填写的数据库的网站。

好的,一切都很好,这部分工作正常。我正在苦苦挣扎的是,每当用户将数据插入数据库时​​,我都想显示一条消息,说明他的插入已成功完成,或者类似的事情。我想在表单面板中显示它。

这是我目前得到的代码:

这是用户点击提交按钮时调用的方法:

[HttpPost]
public ActionResult Create(PersonModels person)
{
    try
    {
        // TODO: Add insert logic here
        //Adding to database and holding the response in the viewbag.
        string strInsertion = ConnectionModels.insertPerson(person);
        ViewBag.InsertionResult = strInsertion;

        return RedirectToAction("Index");
    }
    catch
    {
        return View("Index");
    }
}

这是我的索引操作:

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

最后,这就是我在 index.cshtml 中尝试的内容:

<div>
     <label>
         @ViewBag.InsertionResult
     </label>
</div>

我不会完全发布它,因为它会非常广泛。但这在表单面板的 div 之下。

希望你能帮我一把。

提前致谢! :)

【问题讨论】:

标签: c# asp.net model-view-controller


【解决方案1】:

在重定向到另一个操作时,您不能传递 ViewBag 值。如果您在同一个控制器中,您可以使用TempData 在会话中传递值,否则您可以将消息作为参数传递给RedirectionResult,如下所示:

return RedirectToAction("Index", new {message="Your Message"});

然后像这样取回它:

public ActionResult Index(string message)
{
    ViewBag.ViewBag.InsertionResult = message;
    return View();
}

这是传递消息的一般方式,但我会推荐这样的方式:

使用BaseController,其中所有控制器都继承自该控制器:

在这里您可以自定义逻辑如何处理全局消息,如错误消息、通知消息、信息消息等。

为此,您需要创建如下模型:

我在这里保持简单:

public class GlobalMessage
{
   public string Message { get;set;}
   public AlertType AlertType {get;set;}
}
public enum AlertType
{
   Success, Info, Error, Danger//etc
}

BaseController 中你会得到这样的东西:

public abstract class BaseController : Controller
{
    protected GlobalMessage GlobalMessage;
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            if (GlobalMessage!= null)
            {
                filterContext.Controller.ViewBag.GlobalMessage = GlobalMessage;
            }
            else
            {
                GlobalErrorViewModel globalErrorModelView = TempData["GlobalMessage"] as GlobalMessage;

                if (globalErrorModelView != null)
                {
                    filterContext.Controller.ViewBag.GlobalErrorViewModel = globalErrorModelView;
                }
            }
        }
        base.OnActionExecuted(filterContext);
    }

}

此时您只需在Tempdata 中注册新的GlobalMessage,如下所示:

public PeopleController : BaseController
{
    [HttpPost]
    public ActionResult Create(PersonModels person)
    {
        try
        {
            // TODO: Add insert logic here
            //Adding to database and holding the response in the viewbag.
            string strInsertion = ConnectionModels.insertPerson(person);
            TempData["GlobalMessage"] = new GlobalMessage{ AlertType = AlertType.Info, Message = "You have successfully added a new person" }

            return RedirectToAction("Index");
        }
        catch
        {
            return View("Index");
        }
    }
}

接下来是如何在视图中显示数据的最后一步:

我个人使用弹出窗口或模态窗口来执行此操作:例如,在 bootstrap 中,您会编写如下内容:

GlobalMessage globalMessage = ViewBag.GlobalMessage as GlobalMessage;
   @if (globalMessage != null)
    {
        <!-- Modal -->
        <div class="modal fade" id="globalMessage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content panel-@globalMessage .AlertType.ToString().ToLower() remove-border-radius">
                    <div class="modal-header panel-heading">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <p class="h-text-primary">@Html.Raw(globalMessage .Message)</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-@globalMessage .AlertType.ToString().ToLower() remove-border-radius" data-dismiss="modal">Close</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    }

有消息时触发模态:

@if (globalMessage != null)
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#globalMessage').modal('show');
        });
    </script>
}

这个例子是为了展示如何让系统显示不同的消息。简而言之,随心所欲!

【讨论】:

  • 当,这真的很有帮助!非常感谢! :D
  • 我很高兴能帮上忙 :)
【解决方案2】:

ViewBagViewData 对象将在重定向后返回 null 值。它们的内容仅在当前请求期间有效。

还有另一个属性TempData,其内容将承受当前和后续请求,但后续请求。但是,这意味着您可以在调用RedirectToAction 时使用它来传递数据。

[HttpPost]
public ActionResult Create(PersonModels person)
{
    try
    {
        // TODO: Add insert logic here
        //Adding to database and holding the response in the viewbag.
        string strInsertion = ConnectionModels.insertPerson(person);
        TempData[InsertionResult] = strInsertion;

        return RedirectToAction("Index");
    }
    catch
    {
        return View("Index");
    }
}

[HttpGet]
public ActionResult Index()
{
    string strInsertion = TempData[InsertionResult];
    return View("Index", new { InsertionResult = strInsertion });
}

<label>
    @Model.InsertionResult
</label>

这里给出了很好的解释:http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications/

另一种方法是让您的Index 视图采用可选视图模型,其中包含在您的数据库中创建人员的HttpPost 的结果。您可以使用该模型来填充标签的内容。强类型模型 FTW!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2013-04-23
    • 1970-01-01
    相关资源
    最近更新 更多