简体   繁体   中英

How to get property value from dynamic model in MVC razor c#

View:

@model  dynamic

<div class="btn-group">
    <a class="btn btn-default dropdown-toggle btn-select" data-toggle="dropdown" href="#">Select a Country <span class="caret"></span></a>
    <ul class="dropdown-menu">
       @foreach (dynamic m in Model)
       {
          <li><a href="#">"@m.EmployeeName"</a></li>
       }
    </ul>
</div>

Controller :

public ActionResult Index()
        {
             var Employees = Connections.SaleBranch.SqlConn.Query("SELECT EmployeeName,EmployeeID FROM dbo.udft_Employee(@RunDate) WHERE OfficerEmployeeID=@OfficerEmployeeID",
            new { OfficerEmployeeID = 78273, RunDate = DateTime.Now.GetPersianDate() },
            commandType: CommandType.Text).ToList();
            var EmployeesList = Employees.Select(x => new { EmployeeName = x.EmployeeName, EmployeeID = x.EmployeeID }).ToList();

            return View("Point/Index", EmployeesList);
        }

The object m shows 2 properties(EmployeeName,EmployeeID).

在此处输入图片说明

But can't fetch m.EmployeeName value

在此处输入图片说明

Try get desired value via reflection:

@foreach (dynamic m in Model)
{    
    var EmployeeName = m.GetType().GetProperty("EmployeeName").GetValue(m);
    <li><a href="#">"@EmployeeName"</a></li>    
}

That's because the objects in employeesList are not dynamic but are anonymous objects. Anonymous can't be used outside the scope they are created in.

A dynamic view model is not a good idea, but if you insist, you can look here . Instead I would make a strongly typed model for the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM