Programing

ASP.NET MVC의 ViewBag 작동 방식

lottogame 2020. 8. 30. 09:21
반응형

ASP.NET MVC의 ViewBag 작동 방식


ASP.NET MVC는 어떻게 ViewBag작동합니까? MSDN은 그것이 Object나를 흥미롭게 하는 단지라고 말합니다. ViewBag.Foo그리고 매직 스트링과 같은 "매직"속성은 ViewBag["Hello"]실제로 어떻게 작동합니까?

또한 ASP.NET WebForms 앱에서 어떻게 만들어서 사용할 수 있습니까?

예는 정말 감사하겠습니다!


ViewBag유형 dynamic이지만 내부적으로System.Dynamic.ExpandoObject()

다음과 같이 선언됩니다.

dynamic ViewBag = new System.Dynamic.ExpandoObject();

이것이 당신이 할 수있는 이유입니다 :

ViewBag.Foo = "Bar";

샘플 확장기 개체 코드 :

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

이것은 동적 개체입니다. 즉, 컨트롤러에서 속성을 추가하고 나중에보기에서 읽을 수 있습니다. 기본적으로 동적 유형의 기능인 개체를 만드는 것처럼 만들기 때문입니다. 역학에 대한 MSDN 문서참조하십시오 . MVC와 관련된 사용법에 대해서는 이 기사참조하십시오 .

If you wanted to use this for web forms, add a dynamic property to a base page class like so:

public class BasePage : Page
{

    public dynamic ViewBagProperty
    {
        get;
        set;
    }
}

Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:

<%= ViewBagProperty.X %>

That should work. If not, there are ways to work around it.


The ViewBag is an System.Dynamic.ExpandoObject as suggested. The properties in the ViewBag are essentially KeyValue pairs, where you access the value by the key. In this sense these are equivalent:

ViewBag.Foo = "Bar";
ViewBag["Foo"] = "Bar";

ViewBag is used to pass data from Controller Action to view to render the data that being passed. Now you can pass data using between Controller Action and View either by using ViewBag or ViewData. ViewBag: It is type of Dynamic object, that means you can add new fields to viewbag dynamically and access these fields in the View. You need to initialize the object of viewbag at the time of creating new fields.

e.g: 1. Creating ViewBag: ViewBag.FirstName="John";

  1. Accessing View: @ViewBag.FirstName.

ViewBag is of type dynamic. More, you cannot do ViewBag["Foo"]. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.

Internal implementation of ViewBag actually stores Foo into ViewData["Foo"] (type of ViewDataDictionary), so those 2 are interchangeable. ViewData["Foo"] and ViewBag.Foo.

And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.


ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view. In controller......

public ActionResult Index()
{
    ViewBag.victor = "My name is Victor";
    return View();
}

In view

@foreach(string a in ViewBag.victor)
{
     .........
}

What I have learnt is that both should have the save dynamic name property ie ViewBag.victor


public dynamic ViewBag
{
    get
    {
        if (_viewBag == null)
        {
            _viewBag = new DynamicViewData(() => ViewData);
        }

        return _viewBag;
    }
}

참고URL : https://stackoverflow.com/questions/14896013/how-viewbag-in-asp-net-mvc-works

반응형