且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#MVC CMS-自定义远程验证

更新时间:2022-11-12 20:27:56

您需要添加参数以将模型的ID属性作为AdditionalFields传递.假设其int Id,然后

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

,方法应该是

public JsonResult IsViewNameAvailable(string viewName, int? id)

请注意,在Edit视图中,您为Id属性包括了一个隐藏的输入,因此其值将由jquery.validate远程功能回传.

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.

然后您可以检查id参数是否为null(即它是新的)或具有值(已存在)并调整查询以适合.

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

当前发生的情况是Remote仅发布了ViewName属性的值,并且由于您的参数是模型,因此将使用默认的id值(0)进行初始化,而您的查询被翻译为Any(v => v.ViewName == viewName && v.Id != 0);

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

我还建议您使用视图模型,而不是您的partial class

I also recommend using a view model rather that your partial class

侧面说明:从生成suggestedViewName的代码中,您期望许多具有相同值的ViewName,这意味着您可能在for循环内进行了许多数据库调用.您可以考虑使用linq .StartsWith()查询来获取所有以ViewName值开头的记录,然后检查循环中设置的内存.

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.