0

ValidationSummary 仅在我传入exception.Message.

如果我通过,它什么也不显示exception

AddModelError接受 Exception 类型。

如何显示Exception

.cshtml:

@model ControlTower2.Models.ViewModelUploadRawMaterial

@{
    ViewBag.Title = "UploadRawMaterialSupplierData";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>UploadRawMaterialSupplierData</h2>

<div>
    @using (Html.BeginForm("UploadRawMaterialSupplierData", "PurchaseOrder", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <table>
            <tr>
                <td>
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                </td>
            </tr>
            <tr>
                <td>
                    @Html.TextBoxFor(model => model.uploadFile, "", new { type = "file" })
                </td>
                <td>
                    @Html.ValidationMessageFor(model => model.uploadFile, null, new { @class = "text-danger" })
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="Upload" />
                </td>
            </tr>
        </table>
    }
</div>

行动结果:

[HttpPost]
public ActionResult UploadRawMaterialSupplierData(ViewModelUploadRawMaterial viewModelUploadRawMaterial)
{
    try
    {
        throw new Exception("test UploadRawMaterialSupplierData error!");
    }
    catch (Exception exception)
    {
        ModelState.AddModelError("", exception);
        return View(viewModelUploadRawMaterial);
    }
}

查看型号:

public class ViewModelUploadRawMaterial
{
    [Required(ErrorMessageResourceType = typeof(Resources.UploadPurchaseOrder), ErrorMessageResourceName = "errorUploadFileRequired")]
    public HttpPostedFileBase uploadFile { get; set; }

    public List<UploadExcelError> UploadExcelErrors { get; set; }
}
4

1 回答 1

0

ModelState.AddModelError()接受一个string值。它主要用于在屏幕上显示友好的错误,以便用户查看出现问题。

您可以分析异常并添加您自己设计的附加“内部代码”,用户可以引用该代码来帮助您调查任何问题?

例如,抱歉,完成您的操作时出现问题 [ERR:1234]1234您的内部参考在哪里)。

或者,如果您想输出整个 Exception 而不管 UX,您可以Newtonsoft JSON.NET通过 Nuget 安装包并将 Exception 序列化为通过它传递的字符串,如下所示:

[HttpPost]
public ActionResult UploadRawMaterialSupplierData(ViewModelUploadRawMaterial viewModelUploadRawMaterial)
{
    try
    {
        throw new Exception("test UploadRawMaterialSupplierData error!");
    }
    catch (Exception exception)
    {
        string jsonException = JsonConvert.SerializeObject(exception);
        ModelState.AddModelError("", jsonException);
        return View(viewModelUploadRawMaterial);
    }
}
于 2018-11-23T11:01:19.443 回答