从数据库中获取数据并使用viewmodel

时间:2016-04-02 13:08:39

标签: c# asp.net asp.net-mvc

我试图在某些引导程序文本框中显示某些数据。

通常在Webforms中我设置一个数据集,并使用类似TextBox.Text=Datatable.Rows[0]["FieldName"].ToString()之类的东西设置文本框的.Text属性,但是对MVC来说是新手让我一无所知。

无论如何,这就是我所拥有的

我有一个像这样的动作结果,我从DB获取数据。数据很好。我需要做的就是让他们联系在一起。

public ActionResult CompanySettings()
        {
            ClaimsIdentity identity = (ClaimsIdentity)User.Identity;
            int CompanyId = Convert.ToInt32(identity.FindFirst("CompanyId").Value);
            //-----------------------------
            ViewBag.CompanyId = CompanyId;
            ViewBag.Page = "Inbox";
            string Name = identity.Name;
            string CompanyName = identity.FindFirst("CompanyName").Value;



            ViewBag.Name = Name;
            ViewBag.CompanyName = CompanyName;
            //-----------------------------

            DataSet ds = CompanyDB.Company_Get_Info(CompanyId);
            return View();
        }

和我的ViewModel(仅显示一个字段作为示例)

public class CompanySettingViewModel
    {
        [Display(Name = "CompanyType")]
        public CompanyType CompanyType { get; set; }

        //and many more fields like this.
    }

我在任何情况下都发布我的HTML部分

<table>
  <tr>
    <td>
      <div class="registerbox-textbox">
          <h6>Company Type</h6>
       @Html.Bootstrap().TextBoxFor(t=>t.CompanyType).Placeholder("FirmaTipi")
      </div>
    </td>
//again many repeating same type fields inside a table
<tr>
<table>

这可能是非常简单和容易的事情,但我被困住了。有没有人有任何想法?

1 个答案:

答案 0 :(得分:4)

public ActionResult CompanySettings()
    {
        ClaimsIdentity identity = (ClaimsIdentity)User.Identity;
        int CompanyId = Convert.ToInt32(identity.FindFirst("CompanyId").Value);
        //-----------------------------
        ViewBag.CompanyId = CompanyId;
        ViewBag.Page = "Inbox";
        string Name = identity.Name;
        string CompanyName = identity.FindFirst("CompanyName").Value;



        ViewBag.Name = Name;
        ViewBag.CompanyName = CompanyName;
        //-----------------------------

        DataSet ds = CompanyDB.Company_Get_Info(CompanyId);
        CompanySettingViewModel NewModel= new CompanySettingViewModel();
        NewModel.CompanyType = "AnyValue" //Pass the Company Type value to model 
        return View(NewModel);
    }

,您的观点将是

  <table>
  <tr>
    <td>
      <div class="registerbox-textbox">
          <h6>Company Type</h6>
       @Html.TextBoxFor(t=>t.CompanyType,  new { @placeholder = "FirmaTipi" })
      </div>
    </td>
//again many repeating same type fields inside a table
<tr>
<table>