有没有办法使用 Remote
属性将参数(不是字段名称)从 Model
类发送到 Controller
。
例如,我有这个 Model
类:
public class SubCategory
{
[Key]
public int ID { get; set; }
public string ClassName
{
get { return "SubCategory"; }
}
[StringLength(450)]
[Remote("IsSubCategoryExist", "Products", AdditionalFields = "ID, ClassName",
ErrorMessage = "Product name already exists")]
public virtual string Name { get; set; }
public virtual string ParentName { get; set; }
}
当 Remote
被触发。可以实现吗?
更新:
Controller 代码:
public async Task<JsonResult> IsSubCategoryExist(string Name, int? ID, string ClassName)
{
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == ClassName);
if (type != null)
{
DbSet dbSet = _dbContext.Set(type);
List<object> subCategories;
if(ID == null)
{
subCategories = await dbSet.Where("Name == @0", Name)
.Take(1).ToListAsync();
}
else
{
subCategories = await dbSet.Where("Name == @0 and Id != @1", Name,ID)
.Take(1).ToListAsync();
}
if(subCategories.Count > 0)
{
return Json(false,JsonRequestBehavior.AllowGet);
}
return Json(true,JsonRequestBehavior.AllowGet);
}
else
{
throw new Exception("Table name does not exist with the provided name");
}
}
最佳答案
我想您可以使用静态值向模型添加一个字段,然后将其添加到 AdditionalFields:
public string ClassName { get {return "SubCategory";} }
[Remote("IsSubCategoryExist", "Products", AdditionalFields = "ID, ClassName",
ErrorMessage = "Product name already exists")]
public virtual string Name { get; set; }
关于c# - 在 MVC 中发送远程属性的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54551577/