ASP.NET MVC 隐藏输入作为附加字段作为 null 发送到远程验证器

ASP.NET MVC hidden input as addtional fields sent as null to remote validator

我的远程验证有问题。

以下是我的模型:

[MetadataType(typeof(M_ToolingAnnotation))]
public partial class M_Tooling
{ 
    public string ToolingID { get; set; }
}

internal sealed class M_ToolingAnnotation
{
    [Required]
    [Display(Name = "Tooling ID")]
    [StringLength(50, ErrorMessage = "The {0} must be less than 50 characters long.")]
    [Remote("CheckToolingID", "Tooling2", AdditionalFields = "ToolingID_Ori", ErrorMessage = "Tooling ID already in use!")]  
    public string ToolingID { get; set; }
}

public class M_ToolingViewModels2 : M_Tooling
{
    public M_ToolingViewModels2()
    { 
        this.M_Tooling = new M_Tooling();
    }

    public M_Tooling M_Tooling { get; set; }

    public string LocationID { get; set; } 
}

控制器如下:

public ActionResult Index()
{ 
    ViewBag.ToolingID_Ori = "lalala";

    return View();
}

[HttpGet]
public JsonResult CheckToolingID([Bind(Prefix = "M_Tooling.ToolingID")] string ToolingID, string ToolingID_Ori )
{
    var result = true;

    if (ToolingID != ToolingID_Ori)
    {
        var routingID = db.M_Tooling.Where(u => u.ToolingID == ToolingID).FirstOrDefault();

        if (routingID != null)
        {
            result = false;
            ModelState.AddModelError(string.Empty, "Tooling ID already exists.");
        }
    }

    return Json(result, JsonRequestBehavior.AllowGet);
}

最后的观点:

@Html.Hidden("ToolingID_Ori", (string)ViewBag.ToolingID_Ori);
@Html.LabelFor(model => model.M_Tooling.ToolingID, "Tooling ID*", htmlAttributes: new { @class = "col-md-2 control-label", @style = "color:red" })
@Html.TextBoxFor(model => model.M_Tooling.ToolingID, new { @class = "col-md-2 form-control", @readonly = "readonly" })
@Html.ValidationMessageFor(model => model.M_Tooling.ToolingID, "", new { @class = "col-md-5 text-danger" })

我检查了元素,它显示如下:

在断点处我们可以看到 ToolingID 的值

但不是 ToolingID_Ori

我一直在寻找解决方案,但他们提到名称必须相同,我需要绑定前缀。但是如何为隐藏输入执行此操作?

您需要使用 HiddenFor 将模型映射到视图。