C# MVC CMS - Customising Remote Validation

这一生的挚爱 提交于 2019-11-28 14:49:28

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!