Asp.net mvc Asp Net MVC表单使源html显示为输出

Asp.net mvc Asp Net MVC表单使源html显示为输出,asp.net-mvc,validation,razor,Asp.net Mvc,Validation,Razor,ASP NET 4.6.1 MVC5 复制步骤: Razor View Create.cshtml: @using Microsoft.AspNet.Identity @model DumpZero.ViewModels.GiftViewModel @{ Layout = "~/Views/Shared/_WizardBar.cshtml"; } <div class="container"> <div class="row"> <d

ASP NET 4.6.1 MVC5 复制步骤:

Razor View Create.cshtml:

@using Microsoft.AspNet.Identity
@model DumpZero.ViewModels.GiftViewModel
@{
    Layout = "~/Views/Shared/_WizardBar.cshtml";
}
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <h2 id="PageTitle"></h2>
        </div>
    <div id="editMsg" hidden="hidden" class="col-md-8">
        <h4>@Resources.create_editmsg1</h4>
        <p style="color:red;">@Resources.create_editmsg2</p>
    </div>
</div>
<div class="row">
    @if (Request.IsAuthenticated)
    {
        using (Html.BeginForm("Create", "Gifts", new { id = Model.Product.ID }, FormMethod.Post, new { @class = "contact-form", id = "contact-form", role = "form" }))
        {
            @Html.HiddenFor(x => x.Product.UserID, new { @Value = User.Identity.GetUserId() });
            @Html.HiddenFor(x => x.Product.ID, new { @Value = Model.Product.ID });
            @Html.AntiForgeryToken()
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        @Html.EditorFor(model => model.Product.Name, new { htmlAttributes = new { @class = "form-control", placeholder = Resources.Title } })
                        @Html.ValidationMessageFor(model => model.Product.Name, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-6" id="SubmitID">
                    <div class="form-group">
                        <input type="submit" id="nextBtn" value="@Resources.Create" class="btn btn-primary pull-right" />
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        @Html.DropDownListFor(model => model.selectedCategoryID, Model.CategoryList, Resources.Choose_Parent_Category, htmlAttributes: new { @class = "form-control", id = "selectedCategoryID" })
                        @Html.ValidationMessageFor(model => model.selectedCategoryID, null, new { @class = "text-danger" })
                    </div>
                </div>
                <div class="col-md-6" id="ChildrenDivID">
                    <div class="form-group">
                        @Html.DropDownListFor(model => model.selectedChildCategoryID, Model.ChildCategoryList, Resources.Choose_Child_Category_optional, htmlAttributes: new { @class = "form-control", id = "selectedChildCategoryID" })
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        @Html.EditorFor(model => model.Product.Description, new { htmlAttributes = new { @class = "form-control textarea", rows = "15", placeholder = Resources.Description } })
                        @Html.ValidationMessageFor(model => model.Product.Description, null, new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        }
    }
以及相关控制器httppost方法:

 [HttpPost]
    [Authorize(Roles = "Admin, Users")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(Product product, int selectedCategoryID, int? selectedChildCategoryID)
    {
        if (ModelState.IsValid)
        {
            try
            {
                string productName = product.Name;
                string productDescription = product.Description;
                string message = "";
                string subject = "";

                if (product.ID.HasValue)  //existing product: only user 'owner' is granted editing / TODO: REMOVE ADMIN WHEN TESTING IS OVER
                {
                    int productID = product.ID.Value;
                    if (User.IsInRole("Admin") || User.Identity.GetUserId() == product.UserID) // check admin or product owner
                    {
                        product = db.Products.Find(productID);
                        ProductModified(product);
                        product.Name = productName;
                        product.Description = productDescription;

                        if (selectedChildCategoryID > 0) //subcategory selected
                        {
                            product.CategoryID = selectedChildCategoryID.Value;
                        }
                        else // no subcategory selected
                        {
                            product.CategoryID = selectedCategoryID;
                        }
                        subject = Resources.email_updatedgift_subject;
                        message = Resources.email_updatedgift_content;
                    }
                }
                else  //new product
                {
                    if (selectedChildCategoryID > 0) //subcategory selected
                    {
                        product.CategoryID = selectedChildCategoryID.Value;
                    }
                    else
                    {
                        product.CategoryID = selectedCategoryID;
                    }
                    product.Name = productName;
                    product.Description = productDescription;
                    product.IsDeleted = false;
                    product.IsApproved = false;
                    product.UserID = User.Identity.GetUserId();
                    db.Products.Add(product);
                    subject = Resources.email_newgift_subject;
                    message = Resources.email_newgift_content;
                }
                db.SaveChanges();
                loadViewModelSelectedCategory(fillViewModel(product.ID.Value));
                await sendNewGiftMail(product, message, subject);
                return RedirectToAction("Create", new { id = product.ID });
            }
            catch (Exception e)
            {
                ErrorSignal.FromCurrentContext().Raise(e);
            }
        }

        return RedirectToAction("InternalServerError", "Error", viewModel);
    }
[HttpPost]
[授权(Roles=“Admin,Users”)]
[ValidateAntiForgeryToken]
公共异步任务

当我故意点击“创建”表单输入按钮,将字段留空时,我预计服务器端验证会失败。 下面是答复:

也就是说,作为对我的输入表单的回复,除了完整的html源页面外,什么也没有打印出来。 困惑

以下是Elmah注册的错误:

参数字典包含“DumpZero.Controllers.giftController”中方法“System.Threading.Tasks.Task
1[System.Web.Mvc.ActionResult]创建(DumpZero.Models.Product,Int32,System.nullable
1[System.Int32])的非空类型“System.Int32”参数“selectedCategoryID”的空条目。可选参数必须是引用类型、可为null的类型或声明为可选参数。参数名称:参数


同样:我希望服务器验证或错误会弹出,而不是将razor视图的html源显示为输出。

这很奇怪。无论如何,我认为您应该使用
返回视图(产品)
而不是
返回重定向到操作(“InternalServerError”,“Error”,viewModel)当模型无效时(例如空白字段)。您使用异步操作方法而不是ajax是否有特定原因?@alisson:当modelstate无效时,产品为空,加载视图将失败。无论如何,问题是:1。modelstate无效,因为缺少必需字段,因此重定向应加载errorpage,但不加载2。viewmodel(元数据)中的服务器端验证应该拦截它,并在有问题的字段下显示“此字段是必需的”。3.在任何情况下,这都不能解释为什么显示完整的“”html源页面而不是2。或1。
 [HttpPost]
    [Authorize(Roles = "Admin, Users")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(Product product, int selectedCategoryID, int? selectedChildCategoryID)
    {
        if (ModelState.IsValid)
        {
            try
            {
                string productName = product.Name;
                string productDescription = product.Description;
                string message = "";
                string subject = "";

                if (product.ID.HasValue)  //existing product: only user 'owner' is granted editing / TODO: REMOVE ADMIN WHEN TESTING IS OVER
                {
                    int productID = product.ID.Value;
                    if (User.IsInRole("Admin") || User.Identity.GetUserId() == product.UserID) // check admin or product owner
                    {
                        product = db.Products.Find(productID);
                        ProductModified(product);
                        product.Name = productName;
                        product.Description = productDescription;

                        if (selectedChildCategoryID > 0) //subcategory selected
                        {
                            product.CategoryID = selectedChildCategoryID.Value;
                        }
                        else // no subcategory selected
                        {
                            product.CategoryID = selectedCategoryID;
                        }
                        subject = Resources.email_updatedgift_subject;
                        message = Resources.email_updatedgift_content;
                    }
                }
                else  //new product
                {
                    if (selectedChildCategoryID > 0) //subcategory selected
                    {
                        product.CategoryID = selectedChildCategoryID.Value;
                    }
                    else
                    {
                        product.CategoryID = selectedCategoryID;
                    }
                    product.Name = productName;
                    product.Description = productDescription;
                    product.IsDeleted = false;
                    product.IsApproved = false;
                    product.UserID = User.Identity.GetUserId();
                    db.Products.Add(product);
                    subject = Resources.email_newgift_subject;
                    message = Resources.email_newgift_content;
                }
                db.SaveChanges();
                loadViewModelSelectedCategory(fillViewModel(product.ID.Value));
                await sendNewGiftMail(product, message, subject);
                return RedirectToAction("Create", new { id = product.ID });
            }
            catch (Exception e)
            {
                ErrorSignal.FromCurrentContext().Raise(e);
            }
        }

        return RedirectToAction("InternalServerError", "Error", viewModel);
    }