At the link below I asked a question about how to ensure a field does not already contain the same value (for example when there is a unique constraint on a field which corr
You need to add a parameter to pass the ID property of the model as AdditionalFields
. Assuming its int Id
, then
[Remote("IsViewPathAvailable", "Validation", AdditionalFields = "Id")]
public string ViewName { get; set; }
and the the method should be
public JsonResult IsViewNameAvailable(string viewName, int? id)
Note that in the Edit
view, you include a hidden input for the Id
property, so its value will be posted back by the jquery.validate remote function.
You can then check if the id
parameter is null
(i.e. it's new) or has a value (it's existing) and adjust the queries to suit.
bool isViewNameInvalid;
if (id.HasValue)
{
isViewNameInvalid = db.View.Any(v => v.ViewName == viewName && v.Id != id);
}
else
{
isViewNameInvalid = db.View.Any(v => v.ViewName == ViewName);
}
What is currently happening is that the Remote
is only posting the value of the ViewName
property, and because your parameter is the model, it is initialized with the default id
value (0
) and your query is translated to Any(v => v.ViewName == viewName && v.Id != 0);
I also recommend using a view model rather that your partial class
Side note: from the code that generates suggestedViewName
, your expecting a lot of ViewName
with the same value, meaning your possibly making numerous database calls inside you for
loop. You could consider using linq .StartsWith()
query to get all the records that start with your ViewName
value, and then check the in-memory set in your loop.