部分视图与控制器和模型的链接

时间:2017-02-27 10:42:11

标签: asp.net-mvc razor asp.net-core-mvc asp.net-mvc-partialview

我是.Net和MVC的新手,我似乎遇到了一个我无法解决的问题。我正在尝试遵循几个教程,但在部分视图方面我失败了。我在这里和不同的网站上查找了很多答案,但仍然无效。我无法弄清楚我做错了什么。

这是我的部分控制者:

 public class PartialController : Controller
  {
    public ActionResult _PartialView()
    {
        var model = new Partial();
        model.Count = 2;

        return PartialView(model);
    }
  }

这是我的部分观点:

@model WebApplication1Tutorial.Models.Partial
<div>
The magic number is: 
@Html.DisplayFor(model => model.Count) 
</div>

我通过以下命令在Index.cshtml中调用此视图:

<div>
@Html.Partial("/Views/Partial/_PartView.cshtml",new Partial())
</div>

最后这是模型:

public class Partial
{
    public int Count { get; set; }
}

我尝试的所有内容都会显示显示文字和数字0的网页。我真的不知道还能做什么。我知道这很容易,但我看不到它。

感谢您的帮助。

编辑。索引视图的代码:

@model MovieGenreViewModel
@{
  ViewData["Title"] = "Index";
 }

<h2>Index</h2>

<p>
 <a asp-action="Create">Create New</a>
</p>

<form asp-controller="Movies" asp-action="Index" method="get">
<p>
    <select asp-for="movieGenre" asp-items="Model.genres">
        <option value="">All</option>
    </select>

    Title: <input type="text" name="SearchString" >
    <input type="submit" value="Filter" />
</p>
</form>

<table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.movies[0].Genre)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.movies[0].Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.movies[0].Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.movies[0].Rating)
        </th>
        <th></th>
    </tr>
</thead>
<tbody>
@foreach (var item in Model.movies) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Genre)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ReleaseDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Rating)
        </td>
        <td>
            <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
            <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
            <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
        </td>
    </tr>
}
</tbody>
</table>

<div>
@{ Html.RenderAction("_PartialView"); }
</div>

1 个答案:

答案 0 :(得分:0)

当您使用@ Html.Partial传递部分内容时,也会传递一个新模型,并且不会调用_PartialView()方法,因此模型不会填充值2。 你可以使用@ Html.Action helper:

unit myclass;

interface

uses
  Classes;

type
....