如何在ViewModel中使用Html.RenderPartial

时间:2015-06-09 13:13:56

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-partialview renderpartial

我正在尝试在每个产品下创建用户评论,我使用Html.RenderAction

 Html.RenderAction("ProductReviewTest", new { id = productids });

它工作正常,但加载带有评论的产品页面需要9.4秒,所以尝试了Html.RenderPartial但是给出了错误

我的产品视图

@model MVCProduct.Models.Product

<!--here displaying products-->

<!--displaying reviews in same view-->

<div class="display-field">
<p> Reviews for @Html.DisplayFor(model => model.ProductTitle) </p>
@{ 

int productid = Model.ProductID;

Html.RenderPartial("ProductReviewTest", new { id = productid });

}

</div>

我的评论视图模型:

public class ProductViewModel
{
    public int ReviewId { get; set; }
    public int? ProductID { get; set; }
    public string ReviewTitle { get; set; }
    public string ReviewMessage { get; set; }
    public int? Rating { get; set; }
    public string CustomerName { get; set; }
    public string ReviewStatus { get; set; }

}

我的ViewResult:

 public PartialViewResult ProductReviewTest(int id)
    {

    List<ProductViewModel> productviewmodel = (from a in dbo.ProductReviews 
    where a.ProductID ==id
    select new ProductViewModel
        {
             ReviewId=a.ReviewId, 
             ProductID=a.ProductID,
             ReviewTitle =a.ReviewTitle,
             ReviewMessage =a.ReviewMessage,
             Rating =a.Rating,
             CustomerName =a.CustomerName,
             ReviewStatus=a.ReviewStatus
        }).ToList();



        return PartialView(productviewmodel);
    }

我的评论视图:

   @model IEnumerable<MVCProduct.Models.ProductViewModel>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ReviewId)
        </th>
.......

</table>

错误:

  

传递到字典中的模型项是类型的   &#39;&LT;&GT; f__AnonymousType5 1[System.Int32]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [Review.Models.ProductViewModel]&#39;

任何帮助都会很棒。

3 个答案:

答案 0 :(得分:2)

RenderActionRenderPartial之间存在差异。在第一个你正在调用action,但在第二个,你直接调用partial view。

因此,您无法在productId中传递RenderPartial,而是需要传递List<ProductViewModel>。同样在RenderPartial中,您需要提供部分视图名称,而不是操作名称。

答案 1 :(得分:1)

<强>的ViewResult:

public PartialViewResult ProductReviewTest()
{
    return PartialView();
}

产品视图

@model MVCProduct.Models.Product

<!--here displaying products-->

<!--displaying reviews in same view-->

<div class="display-field">
<p> Reviews for @Html.DisplayFor(model => model.ProductTitle) </p>
@{ 

int productid = Model.ProductID;

Html.RenderPartial("ProductReviewTest", Model.ProductReviews });

}

</div>

答案 2 :(得分:0)

您要返回要查看的ProductViewModel列表。 而是使用

.....
.....
$con=mysqli_connect("mysite","user","mypass","mydb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$data = json_decode(file_get_contents("php://input"));
$id = mysqli_real_escape_string($con, $data->id);
$sql = "UPDATE invites SET status='rejected' where id ='$id'";
....
....

返回PartialView(productviewmodel);