I have a model ModelA
with a member toBeRemoteChecked
and a model MapToA
with a member valueToMap
. Whenever I create an instance of ModelA
, I also need an instance of MapToA
, so I have a model CreateModelA
which includes a member modelA
and a member valueToMap
. When the form is submitted, I add the modelA
to the database table ModelA
and create and add an instance to MapToA
which consists of an id of modelA
and the valueToMap
. In Terms of code
public class ModelA
{
[Key]
public int ID { get; set; }
[Required, Remote("isValid", "MyController", ErrorMessage = "not valid")]
public string toBeRemoteChecked { get; set; }
}
public class MapToA
{
[Key]
public int Map_ID { get; set; }
[Required]
public int modelAID { get; set; }
[Required]
public int valueToMap { get; set; }
}
public class CreateModelA
{
public ModelA modelA { get; set; };
public int valueToMap { get; set; };
}
When I edit an instance of ModelA
, values in MapToA
don't matter (and in most cases there's more than one instance of mapToA
with the same modelA
id), but the remote validation of toBeRemoteChecked
remains important.
My Problem: binding for the validation method:
public ActionResult isValid(string toBeRemoteChecked) { ... }
If I leave it as it is, it is working when editing a ModelA
, but not when I'm creating a ModelA
via CreateModelA
(I always get null value in toBeRemoteChecked
). When I use the BindPrefix
public ActionResult isValid([Bind(Prefix = "modelA.toBeRemoteChecked")] string toBeRemoteChecked) { ... }
it is working when I create a ModelA
, but not when I'm editing it.
When I try to change the "name" in the Create.cshtml by adding a ... @Name = "toBeRemoteChecked" ...
(instead of the modelA.toBeRemoteChecked
that's created by the HTML helper) in the htmlAttributes of the @Html.TextBoxFor
, then validation is working, but the binding of the value to the table get's lost and I get the error when the values are saved to the database (null value).
So, how do I achieve the different binding for creating and editing?
So far, my workaround is to make ModelA
and CreateModelA
: IValidatableObject
and check the member toBeRemoteChecked
in my public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
method. But that one displays the error messages on top of the form and not at the place of the TextFor box.
So: best solution: how to do the binding that the remote validation works in both cases?
Second best: how to display the error messages of IValidatableObject
near the object where it belongs to (and get the error messages right at hand, not after submitting)
Different ideas or solutions: welcome.
Thanks.