2017-05-25 60 views
1

我最近学习了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,所以无论何时插入东西,它都会刷新局部视图。

+0

请检查我的答案波纹管 –

回答

1

装入局部视图这样,

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

而在你ViewPrescription方法,返回的数据,

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

希望它能帮助。

+1

它的工作原理!非常感谢。 – kielou

+1

很高兴它工作:)请标记为答案。 –

+0

谢谢,现在我可以继续申请阿贾克斯了 – kielou

0

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

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

     return PartialView(model); 
    } 
相关问题