MVC-未找到“索引”或其母版

时间:2018-12-17 14:33:38

标签: c# asp.net asp.net-mvc razor view

我收到一条错误消息,提示:

df1 <- structure(list(First.Name = c("John", "John", "John", "Lisa", 
"Lisa"), Last.Name = c("Mars", "Mars", "Mars", "Smith", "Smith"
), Country = c("UK", "UK", "UK", "USA", "USA"), Unit = c("Sales", 
"Sales", "Sales", "HHRR", "HHRR"), Hospital = c("South", "South", 
"South", "North", "North")), .Names = c("First.Name", "Last.Name", 
"Country", "Unit", "Hospital"), class = "data.frame", row.names = c(NA, 
-5L))

df2 <- structure(list(First.Name = c("John", "Peter", "Frank", "Marie", 
"Lisa", "John"), Last.Name = c("Valjean", "Smith", "Mars", "Valjean", 
"Smith", "Mars"), ID = 1254:1259), .Names = c("First.Name", "Last.Name", 
"ID"), class = "data.frame", row.names = c(NA, -6L))

我看过几篇关于此的文章,但这些答案都没有解决我的问题。我尝试在Visual Studio中单击视图,然后将其转到适当的方法。我尝试添加具有主视图和索引的主控制器,但这也无济于事。我尝试修改我的路由配置,但也没有用。

这是我的退货声明,给我一些问题:

Exception Details: System.InvalidOperationException: The view 'Index' or its 
master was not found or no view engine supports the searched locations. The 
following locations were searched:
~/Views/Request/Index.aspx
~/Views/Request/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Request/1819.master
~/Views/Shared/1819.master
~/Views/Request/1819.cshtml
~/Views/Request/1819.vbhtml
~/Views/Shared/1819.cshtml
~/Views/Shared/1819.vbhtml

我正在调用此方法:

return View("Index", requestVM.AidYear);

我尝试过:

public ActionResult Index(string aidYear)

我尝试过:

return View("Index", (object)requestVM.AidYear);

最后2个得到:

return View("Index", model:requestVM.AidYear);

这发生在我的本地计算机和生产服务器上。我所在的团队在发布该文件时确定该文件正在运行,因为这是一个尚未注意到的大问题,因此我们不确定为什么它不再起作用。自发布此应用程序以来,没有对生产进行任何更改,因此我们知道没有人做任何事情来搞砸它。

以防万一,这是我的路线配置:

System.InvalidOperationException: The model item passed into the dictionary is of type 'System.String', but this dictionary requires a model item of type 'ScholarshipDisbursement.ViewModels.Request.RequestViewModel'.

编辑: 在我看来,我有一个“请求”文件夹,并且在该文件夹内是一个Index.cshtml。在该视图上,我有一个表单提交给方法SubmitScholarshipRequest。该方法在请求控制器上。

在该方法中,我运行各种检查,如果有错误,则将其添加到ModelState中。如果ModelState无效,则:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Request", action = "Index", id = UrlParameter.Optional }
        );
    }

否则我:

return View("Index", requestVM.AidYear);

这是我的观点:

return RedirectToAction("Index", "Request", new { @aidYear = requestVM.AidYear });  

这是表单调用的方法:

@using ScholarshipDisbursement.Helpers
@using ScholarshipDisbursement.ViewModels.Request
@model RequestViewModel

@{
ViewBag.Title = "Scholarship Request";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="requestIndexRoundedShadow">

<div class="pageTitleHeader">
    <span><img src="~/Content/img/gradCap.ico" class="headerImg" /></span>
    <span class="headerTitle"><b>Scholarship Disbursement Request</b></span>
        <hr style="border-top: 1px solid black">

@using (Html.BeginForm("SubmitScholarshipRequest", "Request", 
FormMethod.Post, new { id = "SubmitTutorRequestFrm" }))
{
    @Html.AntiForgeryToken()

    <span id="aidYearLbl" Style="font-size: 14px;font-weight: bold">Academic 
Year: </span>
    @Html.DropDownListFor(m => m.AidYear, new SelectList(Model.AidYears, 
"Code", "Name"), new { id = "aidYear", onchange = "onChangeYear()", Style = 
"font-size: 14px" })

    if (Model.Scholarships.Any())
    {
        <br />
        <br />

        <table style="width: 100%;">
            <tr>
                <th class="headerBox tableHeader" colspan="3">Scholarships 
for @Model.User.DeptName</th>
            </tr>
            <tr>
                <th class="headerBox columnHeader" style="width: 
500px;">Scholarship Name</th>
                <th class="headerBox columnHeader" style="width: 
100px;">Amount</th>
                <th class="headerBox columnHeader" style="width: 
100px;">Requested</th>
            </tr>
            @{ int i = 1; }
            @foreach (var s in Model.Scholarships)
            {
                var rowColor = i % 2 == 0 ? "E8E8E8" : "ffffff";
                <tr style="background-color: #@rowColor;">
                    <td class="rowValue">@Html.ActionLink(s.Name, 
"ScholarshipRequest", "Request", new { aidYear = s.AidYear, fundCode = s.Id, 
}, new { target = "_blank" })</td>
                    <td class="rowValue">@s.AmountTotal</td>
                    <td class="rowValue">@s.AmountRequested</td>
                </tr>
                i++;
            }
        </table>

        <br />
        <br />

        if (Model.AvailScholarships.Any())
        {
            <table style="width: 100%">
                <tr>
                    <th class="headerBox tableHeader" colspan="6">Request 
Scholarship</th>
                </tr>
                <tr>
                    <th class="headerBox columnHeader">Scholarship</th>
                    <th class="headerBox columnHeader">Banner Id</th>
                    <th class="headerBox columnHeader">Student Name</th>
                    <th class="headerBox columnHeader">Amount</th>
                    <th class="headerBox columnHeader">Term</th>
                    <th class="headerBox columnHeader">Comments</th>
                </tr>
                <tr>
                    <td class="rowValue" style="width: 200px">@Html.DropDownListFor(m => m.ScholarshipId, new SelectList(Model.AvailScholarships, "Id", "Name"), "", new { id = "scholars" })</td>
                    <td class="rowValue" style="width: 125px">@Html.TextBoxFor(m => m.StudentId, new { autocomplete = "off", Style = "width:100%", id = "bannerId", maxlength = "9" })</td>
                    <td class="rowValue" style="width: 225px"><span id="studentName"></span></td>
                    <td class="rowValue" style="width: 50px">@Html.TextBoxFor(m => m.Amount, new { autocomplete = "off", Style = "width:100%", id = "amount", Value = "", data_val_number = " " })</td>
                    <td class="rowValue" style="width: 70px">@Html.DropDownListFor(m => m.Term, new SelectList(Model.Terms, "Code", "Name"), "", new { Style = "width:70px", id = "term" })</td>
                    <td class="rowValue" style="width: auto">@Html.TextBoxFor(m => m.Comments, new { autocomplete = "off", Style = "width:100%", id = "comments" })</td>
                </tr>
                <tr>
                    <td>@Html.ValidationMessageFor(m => m.ScholarshipId)</td>
                    <td>@Html.ValidationMessageFor(m => m.StudentId)</td>
                    <td></td>
                    <td>@Html.ValidationMessageFor(m => m.Amount)</td>
                    <td>@Html.ValidationMessageFor(m => m.Term)</td>
                    <td>@Html.ValidationMessageFor(m => m.Comments)</td>
                </tr>
            </table>

            <br />
            <input type="submit" id="SubmitNomineeBtn" name="SubmitNomineeBtn" class="submitButton" value="Submit" />
            <span id="warning"></span>
            <br />
            <br />
            <div class="field-validation-error">
                @Html.ErrorFor(ViewData, "ExceedsAmountError")
            </div>
            <div class="field-validation-error">
                @Html.ErrorFor(ViewData, "DuplicateEntryError")
            </div>
            <div class="field-validation-error">
                @Html.ErrorFor(ViewData, "NullStudent")
            </div>
            <div class="field-validation-error">
                @Html.ErrorFor(ViewData, "NegativeAmount")
            </div>
        }
        else
        {
            <div style="padding-right: 100px">
                <img src="~/Content/img/alert.png" /> There are currently no funds available for the @Model.User.DeptName department.
            </div>
        }

    }
    else
    {
        <br />
        <br />
        <div style="padding-right: 100px">
            <img src="~/Content/img/alert.png" /> There are currently no scholarships available for the @Model.User.DeptName department.
        </div>
    }
}



</div>

<script>

$('#help').click(function() {
    var win = $('#window').data("kendoWindow");
    win.open();
    win.center();
    win.top();
});

$(document).ready(function () {   
    if ($('#bannerId').val()) {
        checkBannerId(); 
    }
});

function checkBannerId() {
    var student = $('#bannerId').val();
    $.ajax({
        type: "POST",
        url: '@Url.Action("GetStudentName","Request")',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ bannerId: student }),  // parameter aNumber
        dataType: "json",
        success: function (msg) {
            if (msg.Result === "Null Student") {
                $('#studentName').html("Error finding student name");
                $('#studentName').css("color", "red");
                $('#bannerId').css("border-color", "red");
                $('#bannerId').css("color", "red");
                $('#warning').html("Invalid Banner Id.");
                $('#warning').css('color', 'red');

                return;
            } else {
                $('#bannerId').css("border-color", "unset");
                $('#bannerId').css("color", "black");
                $('#studentName').html(msg.Result);
                $('#studentName').css('color', 'black');
                $('#warning').html("");
                $('#warning').css('color', 'unset');
            }
        },
        error: function () {
        }
    });
}

function onChangeYear() {
    window.location = '@Url.Action("Index", "Request")?aidYear=' + $("#aidYear").val();
}

$('#amount').blur(function () {
    if (isNaN($('#amount').val()) || $('#amount').val() < 0) {
        $('#warning').html("Invalid amount ($, commas, and negative numbers not allowed).");
        $('#warning').css('color', 'red');
        $('#amount').css("border-color", "red");
        $('#amount').css('color', "red");
    } else {
        $('#amount').css("border-color", "unset");
        $('#amount').css("color", "unset");
        $('#warning').html("");
        $('#warning').css('color', 'unset');
    }
});    

$('#bannerId').blur(function () {
    checkBannerId();
});

</script>

这是RequestController中的索引视图方法:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SubmitScholarshipRequest(RequestViewModel requestVM)
    {
        var scholarshipMgr = new ScholarshipStore();
        var scholarship = scholarshipMgr.GetScholarship(requestVM.ScholarshipId, requestVM.AidYear);
        double amountTotal = scholarship.AmountTotal;
        double amountRequested = scholarship.AmountRequested;
        double addTotal = amountRequested + requestVM.Amount;

        string username = User.Identity.Name;
        var user = new UserStore().GetUser(username);

        var student = new StudentStore().GetStudent(requestVM.StudentId);

        if (student == null)
        {
            ModelState.AddModelError("NullStudent","Unable to find Student");
        }

        var scholarshipRequestMgr = new ScholarshipRequestStore();

        var scholarshipRequest = scholarshipRequestMgr.GetScholarshipRequest(requestVM.StudentId, requestVM.ScholarshipId, requestVM.AidYear);

        if (scholarshipRequest != null)
        {
            ModelState.AddModelError("DuplicateEntryError", "Scholarship already requested for this student!");
        }

        if (addTotal > amountTotal)
        {
            ModelState.AddModelError("ExceedsAmountError", "Amount entered exceeds the total available!");
        }

        if (addTotal < 0)
        {
            ModelState.AddModelError("NegativeAmount", "Must be a positive number");
        }

        if (!ModelState.IsValid)
        {
            var aidYears = new AidYearStore().GetAidYears();
            var scholarships = new ScholarshipStore().GetScholarships(user.DeptCode, requestVM.AidYear);
            var availableScholarships = scholarships.Where(x => x.AmountTotal > x.AmountRequested);
            var terms = new TermStore().GetAllTerms();

            requestVM.AidYears = aidYears;
            requestVM.User = user;
            requestVM.Scholarships = scholarships;
            requestVM.AvailScholarships = availableScholarships;
            requestVM.Terms = terms;

            return View("Index", requestVM.AidYear);
        }

        var scholarShipRequest = new ScholarshipRequest
        {
            AidYear = requestVM.AidYear,
            ScholarshipId = requestVM.ScholarshipId,
            StudentId = requestVM.StudentId,
            Amount = requestVM.Amount,
            TermCode = requestVM.Term,
            Comments = requestVM.Comments,
            DeptId = user.DeptCode,
            DateCreated = DateTime.Now,
            CreatedBy = username,
            PIDM = new StudentStore().GetStudent(requestVM.StudentId).PIDM
        };

        new ScholarshipRequestStore().CreateScholarshipRequest(scholarShipRequest);

        return RedirectToAction("Index", "Request", new { @aidYear = requestVM.AidYear });

    }

3 个答案:

答案 0 :(得分:1)

您的视图似乎具有标题:

@model ScholarshipDisbursement.ViewModels.Request.RequestViewModel

因此,您应该使用:

return View(requestVM);

对于该应用程序,应使用所有viewModel。

否则,我们将需要您的结构以提供更好的帮助。

答案 1 :(得分:1)

您的视图需要RequestViewModel,而不是字符串。因此,仅提供援助年是行不通的。这就是“索引”操作方法所期望的,但是这里我们只是直接加载视图,而不执行该操作方法(毕竟,我们已经在执行一个不同的操作方法)。因此,您需要在return语句中传递整个viewmodel对象。

此外,由于它不是称为“索引”的操作方法,因此您需要指定要返回的视图的名称。

我希望

return View("Index", requestVM);

将解决您的问题。

答案 2 :(得分:0)

我认为提示是在错误消息中。它正在寻找一个名为1819.cshtml的视图。

这是告诉它寻找一个具有requestVM.AidYear值的视图以用于母版页或模板页。

return View("Index", requestVM.AidYear);

如果要将模型传递给视图,请改用此方法。我传递的不是字符串(而不是字符串)(我假设requestVM.AidYear是)。因此,它将使用requestVM作为模型。

return View("Index", requestVM);

或者,这可能就是您想要的。使用

return RedirectToAction("Index", "Request", new { @aidYear = requestVM.AidYear });