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

Maciejd

我正在Uni上为ASP.NET类创建一个简单的MVC项目。它由一个模型类(BikeAds),控制器(BikeAdsController)和视图(创建,删除,详细信息,编辑,索引)组成,并将mdf文件用作数据库。

控制器和视图是自动生成的(我选择了“使用Entity Framework的带有视图的MVC控制器”)。

尝试创建新条目时遇到了问题。当我填写“创建”表单并单击“提交”按钮时,它将清除输入字段中的所有数据,并且不提交表单-验证不允许使用空字段。当我删除[Required]验证时,我得到了一个SQL异常(数据库中不允许为null)。

我不明白问题的根源在哪里。

控制器:

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

型号类别:

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

        }

    }
}
杰丁·贤哲

在HTTPPostCreate方法中,您仅绑定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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

阻止Asp.NET按钮提交表单

来自分类Dev

清除Angular表单提交中的输入字段?

来自分类Dev

提交时清除输入字段

来自分类Dev

ASP.Net MVC 4在表单提交时设置“ onsubmit”

来自分类Dev

在提交表单时以编程方式将所有表单字段设置为ng-touch

来自分类Dev

提交简单表单MVC ASP.Net网站的StackOverflow异常

来自分类Dev

使用URL参数提交Asp.Net表单

来自分类Dev

在Asp.net Core中提交Ajax表单后的RedirectToAction

来自分类Dev

选中“ ASP.NET MVC提交表单”复选框

来自分类Dev

检测已在C#/ ASP.NET中提交的表单

来自分类Dev

如何获得提交ASP.NET VS 2019表单的按钮

来自分类Dev

jQuery UI提交表单ajax asp.net

来自分类Dev

检测已在C#/ ASP.NET中提交的表单

来自分类Dev

使用URL参数提交Asp.Net表单

来自分类Dev

asp.net提交表单后如何获取post数据

来自分类Dev

ASP.NET MVC 5 最佳实践表单提交

来自分类Dev

在 ASP.Net Core 中单击单选按钮提交表单

来自分类Dev

从Knockout向ASP.NET MVC提交表单不会带来所有值

来自分类Dev

ASP.NET MVC AJAX表单提交在提交/发布操作后丢失ListBoxFor / MultiSelectList

来自分类Dev

php表单-提交时清除表单-重置

来自分类Dev

关闭时清除表单输入字段

来自分类Dev

阻止表单中的ASP.NET文本框提交表单

来自分类Dev

如何在ASP.NET Web表单中处理不同的表单提交

来自分类Dev

在React中提交表单后无法清除输入字段

来自分类Dev

ASP.NET网站-在提交之前更改在表单中输入的值

来自分类Dev

提交表单时清除特定字段(不是全部)

来自分类Dev

提交表单时输入被排除

来自分类Dev

清除 Xamarin 表单中的所有字段

来自分类Dev

在ASP.NET中更改部分视图时,如何使表单提交更新的值?

Related 相关文章

热门标签

归档