在一个视图MVC3中使用两个模型类

时间:2012-11-14 07:49:56

标签: asp.net-mvc-3

以下是该方案。我创建了一个父模型类,在一个视图中使用两个模型类。这工作正常,但当我尝试从数据库获取记录时,我收到此错误。传递到字典中的模型项的类型为“PMS_V2.Models.Pension_info”,但此字典需要“PMS_V2.Models.Parentmodel”类型的模型项。

Parentmodel.cs

namespace PMS_V2.Models {
  // it  is the class of the parent model
  public class Parentmodel {
    // calling of pension info
    // for using foreach I have used ienumerable
    public IEnumerable<Pension_info> pension_infos { get; set; }
    //constructor
    public Parentmodel() {
      pension_infos = new List<Pension_info>();
    }
    // class of search
    public Search id { get; set; } // method to get id
  }
}

Search.cshtml

@model PMS_V2.Models.Parentmodel
@{
  ViewBag.Title = "Search";
}
<h2>Search</h2>
<p> Here Pensioner can check his records. Give your Pension_id in search query and get your details.</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">  </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>
@using (Html.BeginForm()) {
  @Html.ValidationSummary(true)
  <fieldset>
    <legend>Pension_info</legend>
    <div class="editor-label">
      @Html.LabelFor(model => model.id, "Pension_no")
    </div>
    <div class="editor-field">
      @Html.TextBoxFor(model=>model.id)  // getting id from user..
      @Html.ValidationMessageFor(model=>model.id)
    </div>
    <p>
      <input type="submit" value="Search" />
    </p>
  </fieldset>
}
<table>
  @foreach (var item in  Model.pension_infos) {
  // model, I think the problem is here
    var i = 0;
    if (i == 0) {
      i++;
      <tr>
        <th>Pension_id</th>
        <th>Name</th>
        <th>P_month</th>
        <th>Amount</th>
      </tr>
    }
    <tr>
      <td>@Html.DisplayFor(modelItem => item.Pen_id)</td>
      <td>@Html.DisplayFor(modelItem => item.Pensioner.Name)</td>
      <td>@Html.DisplayFor(modelItem => item.P_month)</td>
      <td>@Html.DisplayFor(modelItem => item.Amount)</td>
    </tr>
  }
</table>

Pension_infoController.cs

[HttpPost]
public ActionResult Search(string id) {
  var abc = from m in db.Pension_info
  // Linq query to get records
    where m.Pen_id == id
    select m;
    return View(abc.FirstOrDefault());
}

请帮助我......我用Google搜索了很多...

2 个答案:

答案 0 :(得分:2)

错误很简单,您使用Parentmodel强烈输入您的视图,但是将类型Pension_info的模型传递给Pension_info,请尝试将Pension_info添加到Parentmodel列表中在[HttpPost] public ActionResult Search(string id) { var abc = from m in db.Pension_info // Linq query to get records where m.Pen_id == id select m; Parentmodel _x = new Parentmodel(); _x.pension_infos.ToList().Add(abc.FirstOrDefault()); return View(_x); }

{{1}}

答案 1 :(得分:0)

试试这个

[HttpPost]
public ActionResult Search(string id)
{
    Parentmodel p = new Parentmodel();
    p.pension_infos = (from m in db.Pension_info where m.Pen_id == id select m)
                      .FirstOrDefault();
    return view(pension_infos);
}