簡體   English   中英

提交表單時所有輸入字段被清除 ASP.NET

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

我正在為我在 Uni 的 ASP.NET 課程創建一個簡單的 MVC 項目。 它由一個 model class (BikeAds), Controller (BikeAdsController) 和 Views (Create, Delete, Details, Edit, Index) 組成,並使用 mdf 文件作為數據庫。

Controller 和視圖是自動生成的(我選擇“MVC controller with views, using Entity Framework”)。

我在嘗試創建新條目時遇到了問題。 當我填寫“創建”表單並單擊“提交”按鈕時,它會清除輸入字段中的所有數據並且不會提交表單 - 驗證不允許空字段。 當我刪除 [Required] 驗證時,出現 SQL 異常(數據庫中不允許為 null)。

我不明白問題的原因在哪里。

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

創建表單:

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

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()
        {

        }

    }
}

在您的 HTTPPost Create方法中,您只綁定了Id屬性;

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

查看您的創建表單,除了Id之外,您還有其他屬性。

1)你不應該綁定所有其他屬性嗎?

2)不應該自動生成ID嗎?

將您的 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