首页 > 解决方案 > 尝试在控制器中执行 ActionResult 方法时,ASP.NET“找不到资源”

问题描述

我正在尝试向我的 MVC5 应用程序添加一个编辑功能,但是每当我尝试Edit在视图中调用我的方法时Search,我都会收到一条错误消息,指出资源localhost:xxxx/Search/EditClient不存在。

EditClient只是我控制器中的一个方法,我必须返回一个RedirectToAction.

这是我的控制器:

public class SearchController : Controller 
{
    public ActionResult SearchClient() {
        //Just returning the default view for the search page
        return View();
    }

    public ActionResult SearchClient(string SearchId)
    {
        //I do have validations in case the ID doesn't exist, but I'm omitting them from this question to avoid inflating the code.
        Client clientFound = (Client)Session[SearchId];
        //SearchId is the ID attribute for my Client object. If the ID was in the Session variable, it will retrieve the corresponding object and I'll use it for the model in my view.
        return View("SearchClient", clientFound);
    }

    [HttpPost]
    public ActionResult EditClient(Client client)
    {
        Session[client.Id] = client;
        return RedirectToAction("SearchClient");
    }
}

我的观点

@model MVCExample.Models.Client

@{
    ViewBag.Title = "Search";
    ViewBag.Message = "Look for Clients";
}

<h1 class="store-title">@ViewBag.Title</h1>
<h2 class="page-title">@ViewBag.Message</h2>
@using (Html.BeginForm("SearchClient", "Search"))
{
   <p>Search for User ID: @Html.TextBox("SearchId")</p></br>
   <input type="submit" value="Search"/>

   @Html.LabelFor(m => m.FullName), new { @class = "control-label" }
   @Html.EditorFor(m => m.FullName, new { @class = "form-control" }

   <a class="btn btn-primary" href="@Url.Action("EditClient, "Search", FormMethod.Post)">Save Changes</a>
}

我可以成功检索用户并显示他们的数据,但是每当我尝试更改它时(在此示例中,我只为 FullName 创建了一个字段,但我为每个属性创建了一个字段)并保存更改,我被重定向到一个错误页面显示 Search/EditClient 不存在。我认为重定向到一个动作可以解决这个问题,那么为什么我的应用程序似乎试图显示错误的视图?

标签: c#asp.netasp.net-mvcrazor

解决方案


如果需要具有SearchandEdit功能,您可以使用两个Html.BeginForm()


@model MVCExample.Models.Client
@{
    ViewBag.Title = "Search";
    ViewBag.Message = "Look for Clients";
}

<h1 class="store-title">@ViewBag.Title</h1>
<h2 class="page-title">@ViewBag.Message</h2>

@using (Html.BeginForm("SearchClient", "Search"))
{
    <div>
        <p>Search for User ID: @Html.TextBox("SearchId")</p>
        <input type="submit" value="Search" />
    </div>

    <div>
        <br />
        @Html.LabelFor(m => m.FullName)
        @Html.EditorFor(m => Model.FullName)
    </div>
}

@using (Html.BeginForm("EditClient", "Search", FormMethod.Post))
{
    @Html.HiddenFor(m => Model.Id)
    @Html.HiddenFor(m => Model.FullName)
    <br /><input type="submit" value="Save Changes" />
}

[HttpPost]属性应用于EditClient方法:

[HttpPost]
public ActionResult EditClient(Client client)
{
    Session[client.Id] = client;
    return RedirectToAction("SearchClient");
}

不幸的是,在这种情况下不可能使用href="@Url.Action()发送。Post如果要创建href,则需要开始处理@Ajax.ActionLink().


推荐阅读