简体   繁体   English

提交表单时所有输入字段被清除 ASP.NET

[英]All input fields are cleared when submitting the form ASP.NET

I'm creating a simple MVC project for my ASP.NET classes at the Uni.我正在为我在 Uni 的 ASP.NET 课程创建一个简单的 MVC 项目。 It consists of one model class (BikeAds), Controller (BikeAdsController) and Views (Create, Delete, Details, Edit, Index) and uses mdf file as a database.它由一个 model class (BikeAds), Controller (BikeAdsController) 和 Views (Create, Delete, Details, Edit, Index) 组成,并使用 mdf 文件作为数据库。

Controller and views were generated automatically (I chose "MVC controller with views, using Entity Framework"). Controller 和视图是自动生成的(我选择“MVC controller with views, using Entity Framework”)。

I encountered the problem when trying to create a new entry.我在尝试创建新条目时遇到了问题。 When I fill the "Create" form and click "Submit" button, it clears all data from the input fields and the form is not submitted - validation doesn't allow for empty fields.当我填写“创建”表单并单击“提交”按钮时,它会清除输入字段中的所有数据并且不会提交表单 - 验证不允许空字段。 When I removed [Required] validation, I got a SQL exception (null is not allowed in the database).当我删除 [Required] 验证时,出现 SQL 异常(数据库中不允许为 null)。

I do not understand where the cause of the issue my lie.我不明白问题的原因在哪里。

Controller: Controller:

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 bikes_ads.Data;
using bikes_ads.Models;

namespace bikes_ads.Controllers
{
    public class BikeAdsController : Controller
    {
        private readonly BikesAdvertsDbContext _context;

        public BikeAdsController(BikesAdvertsDbContext context)
        {
            _context = context;
        }

        // GET: BikeAds
        public async Task<IActionResult> Index()
        {
            return View(await _context.Adverts.ToListAsync());
        }

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

            var bikeAd = await _context.Adverts
                .FirstOrDefaultAsync(m => m.Id == id);
            if (bikeAd == null)
            {
                return NotFound();
            }

            return View(bikeAd);
        }

        // GET: BikeAds/Create
        public IActionResult Create()
        {
            return View();
        }

        **// POST: BikeAds/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id")] BikeAd bikeAd)
        {
            if (ModelState.IsValid)
            {
                _context.Add(bikeAd);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(bikeAd);
        }**

        // GET: BikeAds/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var bikeAd = await _context.Adverts.FindAsync(id);
            if (bikeAd == null)
            {
                return NotFound();
            }
            return View(bikeAd);
        }

        // POST: BikeAds/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id")] BikeAd bikeAd)
        {
            if (id != bikeAd.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(bikeAd);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BikeAdExists(bikeAd.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(bikeAd);
        }

        // GET: BikeAds/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var bikeAd = await _context.Adverts
                .FirstOrDefaultAsync(m => m.Id == id);
            if (bikeAd == null)
            {
                return NotFound();
            }

            return View(bikeAd);
        }

        // POST: BikeAds/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var bikeAd = await _context.Adverts.FindAsync(id);
            _context.Adverts.Remove(bikeAd);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool BikeAdExists(int id)
        {
            return _context.Adverts.Any(e => e.Id == id);
        }
    }
}

Create form:创建表单:

@model bikes_ads.Models.BikeAd

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>BikeAd</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Category" class="control-label"></label>
                <input asp-for="Category" class="form-control" />
                <span asp-validation-for="Category" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ShortDescription" class="control-label"></label>
                <input asp-for="ShortDescription" class="form-control" />
                <span asp-validation-for="ShortDescription" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LongDescription" class="control-label"></label>
                <input asp-for="LongDescription" class="form-control" />
                <span asp-validation-for="LongDescription" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SellerName" class="control-label"></label>
                <input asp-for="SellerName" class="form-control" />
                <span asp-validation-for="SellerName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SellerPhoneNumber" class="control-label"></label>
                <input asp-for="SellerPhoneNumber" class="form-control" />
                <span asp-validation-for="SellerPhoneNumber" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

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

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

Model class: Model class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace bikes_ads.Models
{
    public class BikeAd
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [MaxLength(50)]
        public string Title { get; set; }
        [Required]
        public string Category { get; set; }
        [Required]
        [MaxLength(100)]
        public string ShortDescription { get; set; }
        [Required]
        [MaxLength(500)]
        public string LongDescription { get; set; }
        [Required]
        public string SellerName { get; set; }
        [Required]
        public string SellerPhoneNumber { get; set; }
        [Required]
        public double Price { get; set; }

        public BikeAd(int id, string title, string category, string shortDescription, string longDescription, string sellerName, string sellerPhoneNumber, double price)
        {
            Id = id;
            Title = title;
            Category = category;
            ShortDescription = shortDescription;
            LongDescription = longDescription;
            SellerName = sellerName;
            SellerPhoneNumber = sellerPhoneNumber;
            Price = price;
        }

        public BikeAd()
        {

        }

    }
}

In your HTTPPost Create method, you're only binding the Id property;在您的 HTTPPost Create方法中,您只绑定了Id属性;

public async Task<IActionResult> Create([Bind("Id")] BikeAd bikeAd)
{
}

Looking at your create form, you have other properties besides Id .查看您的创建表单,除了Id之外,您还有其他属性。

1) Shouldn't you be binding the all the other properties? 1)你不应该绑定所有其他属性吗?

and

2) Shouldn't Id be automatically generated? 2)不应该自动生成ID吗?

Change your Create method to this;将您的 Create 方法更改为此;

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Title,Category,Description,ShortDescription,LongDescription,SellerName,SellerPhoneNumber,Price")] BikeAd bikeAd)
{
   if (ModelState.IsValid)
   {
      _context.Add(bikeAd);
      await _context.SaveChangesAsync();
      return RedirectToAction(nameof(Index));
   }

   return View(bikeAd);
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM