【问题标题】:Populate Form Fields after Submit ASP.NET Core 3.1 MVC提交 ASP.NET Core 3.1 MVC 后填充表单字段
【发布时间】:2020-10-19 02:16:37
【问题描述】:

我正在尝试在提交表单后重新填充我的输入字段(使用 HttpPost)。有没有一种简单的方法可以做到这一点?我有一个下拉列表和一个文本框,其中填充了数据库中的数据。它们在控制器中都有自己的函数来处理数据流。我的目标是在提交后让最后创建的数据出现在输入字段中。

我的模特

public int ID { get; set; }
public string bookName { get; set; }
public string Author { get; set; }

我的观点

<form method="post" asp-controller="Home" asp-action="Home" role="post">
    <div class="form-group">
        <label asp-for="bookName"></label>
        <select name="bookName" asp-items="@(new SelectList(ViewBag.message, "ID", "bookName"))">
</select>
    </div>
    <div class="form-group">
        <label asp-for="Author"></label>
        <input asp-for="Author" class="form-control" />
    </div>
    <div class="form-group">
        <input type="submit" value="Submit" class="btn btn-primary" />
    </div>
</form>

我的控制器

        public void GetBooksDDL()
        {
            List<BookModel> bookName = new List<BookModel>();
            bookName = (from b in _context.BookModel select b).ToList();
            bookName.Insert(0, new BookModel { ID = 0, bookName = "" });
            ViewBag.message = bookName;
        }

        [HttpPost("[action]")]
        [Route("/Home")]
        [Produces("application/json")]
        public async Task<IActionResult> Home()
        {
            if (textbox != "")
            {
                //do all the submit actions
                //after all of the actions are complete return the view:
                GetBooksDDL();
                return View();
            }else
            {
                return Error;
            }
        }

我知道我可以在 View() 中传入模型,但值始终为空。我试图将我的(BookModel 模型)作为参数传入 HttpPost,但我得到了 415 状态。

【问题讨论】:

  • 在 post 操作方法中,您应该再次创建模型对象并将其传递给视图。
  • @Rena,嗨 Rena,感谢您的回复!它对我的问题没有多大帮助。我只使用一个模型,它包含 2 个字符串和一个 int(主键)。我收到这个问题,说尝试在我的 httppost 上设置 viewbag(重置下拉列表)时,模型不能变成 IEnumerable。我应该声明我确实希望最后创建的项目在提交后出现在字段中。谢谢!
  • 嗨@BeeSwift,你的文本框是什么?使用你的代码我无法得到这样的错误。提交后如何维护最后创建的项目,请参阅我的更新。
  • 我的回答对您有帮助吗?还有其他问题吗?
  • 嗨@Rena,感谢您的更新回复。设置 List bookName = new List(); 时遇到问题。错误提示“无法在此范围内声明名为 'bookName' 的本地或参数,因为该名称用于封闭本地范围以定义本地或参数”

标签: c# asp.net-core model-view-controller razor input


【解决方案1】:

我正在尝试在提交表单后重新填充我的输入字段(使用 HttpPost)。

对于简单的输入字段,只需return View(model)。对于SelectList,您需要重新设置值。

这是一个简单的演示,如下所示:

型号:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}
public class Category
{
    public int Id { get; set; }
    public string CName { get; set; }
}

查看:

@model Test
<h1>Edit</h1>

<h4>Test</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div>
                <label asp-for="Category"></label>
                <select asp-for="Category.Id" asp-items="@ViewBag.Category"></select>
                <span asp-validation-for="Category.Id" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

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

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

控制器:

public class TestsController : Controller
{
    private readonly YourDbContext _context;
    private readonly List<Category> categories;
    public TestsController(YourDbContext context)
    {
        _context = context;
        categories = _context.Category.ToList();
    }
    // GET: Tests/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        var test = await _context.Test.FindAsync(id);
        ViewBag.Category = new SelectList(categories, "Id", "CName", test.Category.Id);
        if (test == null)
        {
            return NotFound();
        }
        return View(test);
    }

    // POST: Tests/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, Test test)
    {
        //do your stuff...
        //...
        //repopulate the selectlist
        ViewBag.Category = new SelectList(categories, "Id", "CName", test.Category.Id);
        return View(test);
    }
}

结果:

更新:

Home.cshtml:

@model BookModel

<form method="post" asp-controller="Home" asp-action="Home" role="post">
    <div class="form-group">
        <label asp-for="bookName"></label>
        <select name="bookName" asp-items="@ViewBag.message">
        </select>
    </div>
    <div class="form-group">
        <label asp-for="Author"></label>
        <input asp-for="Author" class="form-control" />
    </div>
    <div class="form-group">
        <input type="submit" value="Submit" class="btn btn-primary" />
    </div>
</form>

家庭控制器:

public IActionResult Home()
{
    GetBooksDDL();
    return View();
}
public void GetBooksDDL(string bookname = "")
{
    List<BookModel> bookName = new List<BookModel>();
    //for easy testing,I just manually set the value
    bookName = new List<BookModel>() {
        new BookModel(){  ID=1, bookName="aaa",Author="aaa"},
        new BookModel(){  ID=2, bookName="bbb",Author="bbb"},
        new BookModel(){  ID=3, bookName="ccc",Author="ccc"}
    };
    bookName.Insert(0, new BookModel { ID = 0, bookName = "" });
    ViewBag.message = new SelectList(bookName, "ID", "bookName", bookname);
}

[HttpPost("[action]")]
[Produces("application/json")]
public async Task<IActionResult> Home(BookModel bookModel)
{            
        //do all the submit actions
        //after all of the actions are complete return the view:
        GetBooksDDL(bookModel.bookName);
        return View(bookModel);
        
}

结果:

【讨论】:

    猜你喜欢
    • 2022-09-26
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多