使用viewbag的MVC Shared Routine

时间:2015-08-11 19:05:06

标签: asp.net-mvc viewbag

我有一个帮助程序例程,我在多个视图中使用它包含一些漂亮的引导程序格式以显示消息。

angular.module('app', [])

.directive('focusSearch', ['$timeout', '$parse', function($timeout, $parse) {
  return {
    link: function(scope, element, attrs) {
      var model = $parse(attrs.focusMe);
      scope.$watch(model, function(value) {
        console.log('value=',value);
        if (value === true) { 
          $timeout(function() {
            element[0].focus();
          });
        }
      });
      // to address @blesh's comment, set attribute value to 'false'
      // on blur event:
      element.bind('blur', function() {
        console.log('blur');
        scope.$apply(model.assign(scope, false));
      });
    }
  }
}])

.controller('sidebar',
['$scope',
 '$rootScope',
 '$timeout',
 function($scope,
          $rootScope,
          $timeout) {

var vs = $scope;

$scope.clickedSearch = function() {
  vs.showingSearchInput = true;
}

$scope.hideSearch = function() {
  vs.showingSearchInput = false;
}

}]);

为了使其工作,我必须简单地使用tempdata(在重定向的情况下),然后将值放回viewbag中。

像这样:

@MyHelpers.StatusMessage(ViewBag.Status, ViewBag.StatusMessage)

我真的希望这是一个像我的助手一样的常见例程,但我无法从那里访问viewbag。

有什么地方我可以放置共享代码并仍然可以访问viewbag吗?

我也愿意采取其他方式做到这一点......我意识到我可能会这么做......

感谢。

决议:

不完美,但允许重复使用并节省几行代码。

@{
    // View Init 

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    // In case we are here due to a redirect... 
    if (!String.IsNullOrEmpty((string)TempData["Status"]))
    {
        ViewBag.Status = TempData["Status"];

    }
    if (!String.IsNullOrEmpty((string)TempData["StatusMessage"]))
    {
        ViewBag.StatusMessage = TempData["StatusMessage"];
    } 

}

1 个答案:

答案 0 :(得分:1)

ViewBag是动态的,因此您可以将其作为共享处理的参数添加到辅助方法中:

public void MyHelperMethod(dynamic viewBag, Dictionary<string, string> tempData)
{
    // In case we are here due to a redirect... 
    if (!String.IsNullOrEmpty((string)tempData["Status"]))
    {
        viewBag.Status = tempData["Status"];
    }

    if (!String.IsNullOrEmpty((string)tempData["StatusMessage"]))
    {
        viewBag.StatusMessage = tempData["StatusMessage"];
    }         
}

P.S。我猜测你的TempData数据类型是字典,请根据需要更正。