You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# ASP.NET Core MVC笑话应用搜索功能失效及视图报错求助

ASP.NET Core MVC笑话应用搜索功能问题解决(无需修改模型)

我编程经验尚浅,目前从事程序员工作,正在自学C#与ASP.NET Core MVC。跟随YouTube教程开发笑话应用时,添加的搜索功能无法返回包含搜索关键词的结果,尝试修改formaction时出现**"The name 'SearchPhrase' does not exist in the current context"**错误,想询问除了修改模型外的解决办法。

我的ShowSearchForm.cshtml代码:

<h4>Search for a Joke</h4>
<hr />
<div class="row">
<div class="col-md-4">
       <form asp-action="ShowSearchResults">
       <div class="form-group">
          <label for="SearchPhrase" class="control-label"></label>
          <input "SearchPhrase" class="form-control" />           
      </div>
      <div class="form-group">
          <input type="submit" value="Search" formaction="@Url.Action("ShowSearchResults", new { SearchPhrase = SearchPhrase})" class="btn btn-primary" />
      </div>
  </form>
</div>
</div>

<div>
<a asp-action="Index">Back to List</a>
</div>

尝试修改的代码:

formaction="@Url.Action("ShowSearchResults", new { SearchPhrase = SearchPhrase})"      

出现的错误:

The name 'SearchPhrase' does not exist in the current context

JokesController代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using JokeWebApp.Data;
using JokeWebApp.Models;
using Microsoft.AspNetCore.Authorization;

namespace JokeWebApp.Controllers
{
    public class JokesController : Controller
    {
        private readonly ApplicationDbContext _context;

        public JokesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Jokes
        public async Task<IActionResult> Index()
        {
            return _context.Joke != null ?
                        View(await _context.Joke.ToListAsync()) :
                        Problem("Entity set 'ApplicationDbContext.Joke'  is null.");
        }

        // GET: Jokes/ShowSearchForm
        public async Task<IActionResult> ShowSearchForm()
        {
            return _context.Joke != null ?
                        View() :
                        Problem("Entity set 'ApplicationDbContext.Joke'  is null.");
        }
    
        // Post : Jokes/ShowSearchResults
        public async Task<IActionResult> ShowSearchResults(String SearchPhrase)
        {
            return View("Index", await _context.Joke.Where(j =>
    j.JokeQuestion.Contains(SearchPhrase)).ToListAsync());
        }

        // GET: Jokes/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Joke == null)
            {
                return NotFound();
            }

            var joke = await _context.Joke
                                     .FirstOrDefaultAsync(m => m.Id == id);

            if (joke == null)
            {
                return NotFound();
            }

            return View(joke);
        }

        [Authorize]
        // GET: Jokes/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Jokes/Create
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,JokeQuestion,JokeAnswer")] Joke joke)
        {
            if (ModelState.IsValid)
            {
                _context.Add(joke);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            return View(joke);
        }

        [Authorize]
        // GET: Jokes/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Joke == null)
            {
                return NotFound();
            }

            var joke = await _context.Joke.FindAsync(id);

            if (joke == null)
            {
                return NotFound();
            }

            return View(joke);
        }

        // POST: Jokes/Edit/5
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,JokeQuestion,JokeAnswer")] Joke joke)
        {
            if (id != joke.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(joke);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!JokeExists(joke.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }

                return RedirectToAction(nameof(Index));
            }

            return View(joke);
        }

        [Authorize]
        // GET: Jokes/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Joke == null)
            {
                return NotFound();
            }

            var joke = await _context.Joke
                                     .FirstOrDefaultAsync(m => m.Id == id);

            if (joke == null)
            {
                return NotFound();
            }

            return View(joke);
        }

        [Authorize]
        // POST: Jokes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Joke == null)
            {
                return Problem("Entity set 'ApplicationDbContext.Joke'  is null.");
            }

            var joke = await _context.Joke.FindAsync(id);

            if (joke != null)
            {
                _context.Joke.Remove(joke);
            }
    
            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        private bool JokeExists(int id)
        {
            return (_context.Joke?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}

Joke模型类代码:

namespace JokeWebApp.Models 
{ 
    public class Joke 
    { 
        public int Id { get; set; } 
        public string JokeQuestion { get; set; } 
        public string JokeAnswer { get; set; } 
        public Joke() { } 
    } 
}

解决办法(无需修改模型):

1. 修复input标签的name属性

你的搜索输入框缺少name属性,导致表单提交时无法将输入的关键词传递给控制器。修改input标签:

<input name="SearchPhrase" id="SearchPhrase" class="form-control" placeholder="输入搜索关键词..." />

name="SearchPhrase"是关键,它要和控制器方法的参数名SearchPhrase一致,这样模型绑定才能正确接收值。

2. 移除submit按钮上的formaction属性

你不需要手动在submit按钮上指定formaction,因为form标签已经通过asp-action="ShowSearchResults"指定了提交目标。之前的formaction代码里试图引用SearchPhrase变量,但这个变量在视图上下文中不存在,所以报错。直接删除formaction属性即可:

<input type="submit" value="Search" class="btn btn-primary" />

3. 优化控制器的搜索逻辑(避免空值报错)

当前控制器的ShowSearchResults方法如果收到空的SearchPhrase,Contains方法会抛出异常。可以添加空值判断,空搜索时返回所有笑话:

// Post : Jokes/ShowSearchResults
public async Task<IActionResult> ShowSearchResults(string SearchPhrase)
{
    var jokeQuery = _context.Joke.AsQueryable();
    
    if (!string.IsNullOrEmpty(SearchPhrase))
    {
        jokeQuery = jokeQuery.Where(j => j.JokeQuestion.Contains(SearchPhrase));
    }
    
    return View("Index", await jokeQuery.ToListAsync());
}

完成以上修改后,搜索功能就能正常工作,而且不需要修改Joke模型类。


内容的提问来源于stack exchange,提问作者Christopher Blick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:36:06