ASP.Net MVC:部分视图无法渲染

时间:2018-01-17 13:03:03

标签: asp.net-mvc

我在asp.net mvc中有点新鲜。我面临着部分视图无法呈现的非常基本的问题。这是细节

我有一个主页面和一个局部视图

主页面操作看起来像

public ActionResult Index()
{
    return View();
}

主索引视图看起来像

@model Testing.Models.Employee

@{
    ViewBag.Title = "Home Page";
}

<div class="row">

</div>

<div class="row">
    <div id="formsIndex">
    @{
        Html.Partial("_TestForm");
    }
    </div>
</div>

@section scripts {
       <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}

这里我显示的是这种方式Html.Partial("_TestForm");的局部视图,但部分视图没有UI。

部分视图代码看起来像

@model Testing.Models.Employee

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "formsIndex" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

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

当我以这种方式将模型传递给局部视图Html.Partial("_TestForm", Model);时,也没有UI来。

请告诉我我犯了哪个错误?

3 个答案:

答案 0 :(得分:1)

在方法中使用返回PartialView()并尝试此

@Html.Partial("_TestForm");

答案 1 :(得分:1)

Html.Partial块中使用@{ ... }只会调用该方法并将结果抛弃。

你应该在@{ ... }块之外调用它,前缀为@,并记住传递模型:

<div id="formsIndex">
@Html.Partial("_TestForm", Model);
</div>

答案 2 :(得分:0)

像这样渲染

@Html.Action("_Partialview", "controllerName")

还创建局部视图的动作方法

public ActionResult _Partialview
{
    Employee _objModel= new Employee ()
    return PartialView(_objModel);
}