如何在同一视图中查看表格和表格

时间:2017-05-25 09:47:24

标签: c# asp.net-mvc

我最近学习ASP.NET MVC5。

我试图在一个视图中看到表单和表格(返回为partialview)但我收到此错误。

System.NullReferenceException: Object reference does not set to an instance of an object.

这是我的模特:

public class Prescription
{
    [Key]
    public int PrescriptionID { get; set; }

    [ForeignKey("Assessment")]
    public int? AssessmentID { get; set; }
    public Assessment Assessment { get; set; }

    [ForeignKey("Medicine")]
    [Display(Name ="Prescription")]
    public int? MedcineID { get; set; }
    public Medicine Medicine { get; set; }
}

我的主要观点,我想放置我的部分观点:

@using ClinicManagemet
@model ClinicManagemet.Models.Prescription


@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Prescription</h4>
    <hr />


    <div class="form-group">

        @Html.LabelFor(model => model.MedcineID, "MedcineID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("MedcineID", null, htmlAttributes: new { @class = "form-control" })

            @Html.ValidationMessageFor(model => model.MedcineID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

     @Html.Action("ViewPrescription","Assessments")

<div>
    @Html.ActionLink("Back to Home", "Home")
</div>

我的部分观点:

@model IEnumerable<ClinicManagemet.Models.Prescription>

 <table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Assessment.Complaint)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Medicine.MedicineName)
    </th>
    <th></th>
</tr>

 @foreach (var item in Model) { //Here is the line where I get the error
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Assessment.Complaint)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Medicine.MedicineName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.PrescriptionID }) |
        @Html.ActionLink("Details", "Details", new { id=item.PrescriptionID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.PrescriptionID })
    </td>
</tr>
 }

 </table>

我的局部视图控制器:

public ActionResult ViewPrescription()
    {
        return PartialView();
    }

编辑:如果我解决这个问题,我会尝试添加Ajax,所以每当我插入一些内容时,它都会刷新局部视图。

2 个答案:

答案 0 :(得分:1)

像这样加载你的局部视图,

@{
    Html.RenderAction("ViewPrescription","YourControllerName") 
 }

在ViewPrescription方法中,返回数据

{
 //Fetch the data here
 return PartialView(model);
}

希望它有所帮助。

答案 1 :(得分:0)

返回视图时,您没有将模型传递到局部视图中。

public ActionResult ViewPrescription()
    {
        ClinicManagemet.Models.Prescription model = _service.GetPerscription();

        return PartialView(model);
    }