[英]Use variable from controller in view ASP.NET MVC4
我的項目中有一個模型
using System;
namespace Argussite.SupplierServices.ViewModels
{
public class UsersPage
{
public Guid SupplierId { get; set; }
public string SupplierFullName { get; set; }
public bool ActionsAllowed { get; set; }
}
}
我在控制器中使用我的模型並設置屬性
public ActionResult Index(Guid id)
{
var supplierOfUser = Context.Suppliers.AsNoTracking()
//.Include(e => e.Supplier)
.FirstOrDefault(e => e.Id == id);
string SupplierId = id.ToString();
string SupplierFullName = supplierOfUser.FullName.ToString();
bool ActionsAllowed = supplierOfUser.Active;
return View();
}
然后我需要在視圖中使用它,但是我不知道如何在視圖中獲取屬性?
首先,您的控制器操作需要將該模型實例發送至視圖,如下所示:
return View(supplierOfUser);
您需要在視圖頂部:
@model Argussite.SupplierServices.ViewModels.UsersPage
然后,您要做的就是在視圖中要使用模型的任何地方:
@Model.SupplierFullName
如果要在視圖中使用其他屬性,可以將其放入動態ViewBag變量中,如下所示:
ViewBag.supplierOfUser = supplierOfUser.FullName.ToString();
然后在您的視圖上,您可以像下面這樣使用該值:
@ViewBag.supplierOfUser
很難為您提供准確的代碼,因為我不知道您想在視圖中做什么,這是您應該如何在視圖中傳遞和使用模型的一般思路
控制者
public ActionResult Index(Guid id)
{
var supplierOfUser = Context.Suppliers.AsNoTracking()
.FirstOrDefault(e => e.Id == id);
var usersPage = new UsersPage
{
SupplierId = supplierOfUser.Id,
SupplierFullName = supplierOfUser.FullName,
ActionsAllowed = supplierOfUser.Active
}
return View(usersPage ); // <-- Send viewmodel to view
}
視圖
// Declare model
@model Argussite.SupplierServices.ViewModels.UsersPage
...
//Use your model here at will
@Html.DisplayFor(modelItem => item.FullName)
...
@Html.EditorFor(model => model.FullName)
@Html.ValidationMessageFor(model => model.FullName)
為了使用從控制器到視圖的數據,您需要使用參數中的模型返回視圖:
return View(supplierOfUser);
在您看來,您還需要定義模型:
@model YourModel
請注意,您無需將供應商信息設置為其他變量(僅需要vendorOfUser)。
創建一個新的UsersPage
並將您已經擁有的屬性分配給它的屬性,然后將新創建的UsersPage
傳遞給視圖:
public ActionResult Index(Guid id)
{
var supplierOfUser = Context.Suppliers.AsNoTracking()
//.Include(e => e.Supplier)
.FirstOrDefault(e => e.Id == id);
var usersPage = new UsersPage();
usersPage.SupplierId = id.ToString();
usersPage.SupplierFullName = supplierOfUser.FullName.ToString();
usersPage.ActionsAllowed = supplierOfUser.Active;
return View(usersPage);
}
最好的方法是在視圖中建立強類型模型:
@model Argussite.SupplierServices.ViewModels.UsersPage
然后,只需引用模型上的屬性,例如
@Html.EditorFor(model => model.SupplierFullName)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.