简体   繁体   English

提交 ASP.NET Core 3.1 MVC 后填充表单字段

[英]Populate Form Fields after Submit ASP.NET Core 3.1 MVC

I am trying to repopulate my input fields after the form has been submitted (with HttpPost).在提交表单(使用 HttpPost)后,我正在尝试重新填充我的输入字段。 Is there a simple way to do this?有没有一种简单的方法可以做到这一点? I have a dropdown and a text box that get populated with data from the database.我有一个下拉列表和一个文本框,其中填充了数据库中的数据。 They each have their own functions in the controller that handle the flow of data.它们在处理数据流的 controller 中都有自己的功能。 My goal is to have the last created data appear in the input fields after submit.我的目标是在提交后让最后创建的数据出现在输入字段中。

My Model我的 Model

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

My View我的观点

<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>

My Controller我的 Controller

        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;
            }
        }

I understand that I could pass in the model in the View(), but the values are always null.我知道我可以在 View() 中传入 model,但值始终是 null。 I tried to pass in my (BookModel model) as an argument in the HttpPost, but I get a 415 status.我试图将我的(BookModel 模型)作为 HttpPost 中的参数传递,但我得到了 415 状态。

I am trying to repopulate my input fields after the form has been submitted (with HttpPost).在提交表单(使用 HttpPost)后,我正在尝试重新填充我的输入字段。

For simple input fields,just return View(model) .For SelectList ,you need set the value again.对于简单的输入字段,只需return View(model) 。对于SelectList ,您需要重新设置值。

Here is a simple demo like below:这是一个简单的演示,如下所示:

Model: Model:

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; }
}

View:看法:

@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");}
}

Controller: Controller:

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);
    }
}

Result:结果: 在此处输入图像描述

Update:更新:

Home.cshtml:主页.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>

HomeController:家庭控制器:

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);
        
}

Result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.Net Core MVC - 表单提交数据成功后运行客户端脚本/函数 - ASP.Net Core MVC - Run client side script/function after form submit data success 提交后如何获取价值 - ASP.NET CORE MVC - How to get value after Submit - ASP.NET CORE MVC 通过 ASP.NET Core 3.1/5.0 MVC 中的脚本使用选定的 ''value='' 填充数据库 - Populate a Datebase with the selected ''value='' through a Script in ASP.NET Core 3.1/5.0 MVC 如何使用 ASP.NET Core 3.1 MVC 和 EF Core 对唯一字段使用数据验证注释? - How do use data validation annotation for unique fields with ASP.NET Core 3.1 MVC and EF Core? 在ASP.NET Core MVC App中添加动态表单字段 - Add dynamic form fields in ASP.NET Core MVC App 在Asp.net Core中提交ajax表单后的RedirectToAction - RedirectToAction after ajax form submit in Asp.net Core 在 ASP.NET MVC 5 中提交表单后返回到同一视图 - Return to same view after form submit in ASP.NET MVC 5 Asp.net核心MVC和JQuery提交 - Asp.net core MVC and JQuery submit 从ASP.NET MVC框架迁移到ASP.NET Core 3.1 MVC后图像不显示 - Image does not display after migration from ASP.NET MVC framework to ASP.NET Core 3.1 MVC ASP.NET 核心 3.1 在 GET 请求上呈现输入字段值不正确的表单 - ASP.NET core 3.1 rendering a form with Incorrect values for Input fields on GET request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM