如何在MVC中不使用ViewBag的情况下在控制器和视图之间共享数据

时间:2015-01-12 06:39:32

标签: c# asp.net-mvc

我创建了一个移动商店项目。我的视图中有一个下拉列表,我需要从数据库填充此下拉列表,因此我在控制器中声明了一个公共变量,但在视图中无法访问它。我也试图声明在模型类中,它工作正常,但问题是,当我从数据库更新实体模型时,这些变量被删除了。所以请建议我如何做到这一点,我也不想使用ViewBag。我试过的代码。

public SelectList Vendor { get; set; }

public ActionResult ShowAllMobileDetails(tbInsertMobile IM)
{                   
     Vendor = new SelectList(db.Usp_VendorList(), "VendorId", "VendorName");
     return View(IM);
}

视图..

@model  MobileApplicationEntityFramework.Models.tbInsertMobile

@{
     ViewBag.Title = "ShowAllMobileDetails";
}

@using (@Html.BeginForm())
{    
    <h2>ShowAllMobileDetails</h2>
    <p>
        @Html.ActionLink("Create New Mobile", "InsertMobile");
    </p>
    <fieldset>
        <legend>Search Panel</legend>
        <table>
            <tr>
                <td>Mobile Name</td>
                <td>@Html.TextBoxFor(a => a.MobileName) </td>
            </tr>
            <tr>
                <td>Mobile Manufacured</td>
                <td>@Html.DropDownList("ddlVendor", Vendor, "Select Manufacurer")</td>
            </tr>            
        </table>
    </fieldset>
}

1 个答案:

答案 0 :(得分:0)

hi: you can define a static property to share to all place in your project:



 public static class Global
    {

    public static SelectList Vendor()
    {
      return (new SelectList(db.Usp_VendorList(), "VendorId", "VendorName"));
    }

    }

and use in your views like this:

            移动制造             @ Html.DropDownList(&#34; ddlVendor&#34;,namespaceOfGlobal.Vendor,&#34;选择Manufacurer&#34;)