【问题标题】:MVC 4 - HttpPost is not firedMVC 4 - 未触发 HttpPost
【发布时间】:2013-07-04 11:24:47
【问题描述】:

我的CreateController.cs

using System.Web.Mvc;
using ClientDAL;
using Services;
using ShardingMvcDemo.Raven;
using ShardingMvcDemo.ViewModels;

namespace ShardingMvcDemo.Controllers
{
    public class CreateController : Controller
    {
        //
        // GET: /Create/

        public ActionResult Index()
        {
            return View();
        }


        //
        // POST: /Create/

        [HttpPost]
        public ActionResult Create(ClientViewModel client)
        {
            try
            {
                var ravenDbConnection = new RavenDbConnection(new RavenDbConnectionManager());
                var service = new ClientService(ravenDbConnection);
                service.AddClient(client.FirstName, client.LastName, client.Country);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

我的Create/Index.cshtml 视图:

@model ShardingMvcDemo.ViewModels.ClientViewModel

@{
    ViewBag.Title = "Create a client";
}

<h2>Create</h2>

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

    <fieldset>
        <legend>Client</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Country)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Country)
            @Html.ValidationMessageFor(model => model.Country)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

当我点击表单中的提交按钮时,[HttpPost] 方法甚至没有被触发(在调试模式下检查)。我做错了什么?

【问题讨论】:

    标签: c# .net asp.net-mvc-4 http-post


    【解决方案1】:

    它与您的视图名称不匹配。将其更改为:

    public ActionResult Index(ClientViewModel client)
    

    【讨论】:

      【解决方案2】:

      也许您应该尝试在表单的初始化中明确定义控制器和操作,如下所示:

      @using (Html.BeginForm("Create", "Create")) { ...

      在您当前的设置中,您尝试 POST 到 /create/index,而不是 /create/create。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-30
        • 1970-01-01
        • 2013-11-23
        • 2016-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多