C # ASP.NET MVC Кнопка Создать не работает при нажатии - PullRequest
0 голосов
/ 05 июля 2019

Моя кнопка создания не работает при нажатии.Может кто-нибудь сказать мне, где я ошибся?

Я пробовал несколько форумов, но они не решили проблему.

Контроллер:

using Rentals.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Rentals.Controllers
{
    public class GenreController : Controller
    {
        private ApplicationDbContext db;

        public GenreController()
        {
            db = new ApplicationDbContext();
        }

        // GET: Genre
        public ActionResult Index()
        {
            return View(db.Genres.ToList());
        }

        //getaction
        public ActionResult Create()
        {
            return View();
        }

        //post action to insert data into database
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Genre genre)
        {
            if (ModelState.IsValid)
            {
                db.Genres.Add(genre);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
        }
    }
}

Просмотр (создать.cshtml):

@model Rentals.Models.Genre
@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())

{
    @Html.AntiForgeryToken()
}

<div class="form-horizontal">
    <h3> Create new Genre</h3>
    <hr />

    <div class="form-group">
        @Html.LabelFor(m=>m.Name, htmlAttributes: new { @class ="control-label col-md-2"})
        <div class="col-md-10">
         @Html.EditorFor(m=>m.Name, new {htmlAttributes = new {@class="form-control"}})
            @Html.ValidationMessageFor(m=>m.Name,"", new { @class = "text-danger"})
        </div>
    </div>
</div>
<div>
    <input type="submit" value="Create" class="btn btn-sm btn-success" />
    @Html.Partial("_BackToListPartial")
</div>

Когда я нажимаю кнопку «Создать», ее следует добавить в базу данных.По какой-то причине, когда я нажимаю на него, он ничего не делает.

1 Ответ

2 голосов
/ 05 июля 2019

Оберните форму вокруг вашего HTML.

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()


<div class="form-horizontal">
    <h3> Create new Genre</h3>
    <hr />

    <div class="form-group">
        @Html.LabelFor(m=>m.Name, htmlAttributes: new { @class ="control-label col-md-2"})
        <div class="col-md-10">
         @Html.EditorFor(m=>m.Name, new {htmlAttributes = new {@class="form-control"}})
            @Html.ValidationMessageFor(m=>m.Name,"", new { @class = "text-danger"})
        </div>
    </div>
</div>
<div>
    <input type="submit" value="Create" class="btn btn-sm btn-success" />
    @Html.Partial("_BackToListPartial")
</div>
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...