Search code examples
c#asp.net-mvchidden-fieldremote-validation

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


I have a problem with my Remote Validation.

The following is my model :

[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; } 
}

The following is the controller :

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);
}

Finally the view:

@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" })

I inspected the element and it showed as below:

enter image description here

and

enter image description here

On breakpoint we can see the value for ToolingID

enter image description here

But not the ToolingID_Ori

enter image description here

I've been searching for solution but they mention the name must be the same and I need to put the prefix bind. But how do I do this for hidden input?


Solution

  • You need to use an HiddenFor to map your Model to the view.