是否有一种方法可以使用Model
属性将参数(不是字段名)从Controller
类发送到Remote
。
例如,我有这个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; }
}
我需要在触发SubCategory
时将此类名IsSubCategoryExist
作为参数发送给Products
控制器中的Remote
方法。可以实现吗?
更新:
控制器代码:
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");
}
}
答案 0 :(得分:2)
我想您可以将一个具有静态值的字段添加到模型中,然后将其添加到AdditionalFields:
public string ClassName { get {return "SubCategory";} }
[Remote("IsSubCategoryExist", "Products", AdditionalFields = "ID, ClassName",
ErrorMessage = "Product name already exists")]
public virtual string Name { get; set; }
答案 1 :(得分:0)
执行以下操作:
public string ClassName { get {return "SubCategory";} }
[Remote("IsSubCategoryExist", "Products", AdditionalFields = "ID, ClassName",
ErrorMessage = "Product name already exists")]
public string Name { get; set; }
您必须按如下所示的形式放置一个隐藏字段,否则将出现ClassName is undefined
错误:
Html.HiddenFor(x => x.ClassName)