【发布时间】:2019-02-07 21:07:30
【问题描述】:
有没有办法使用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 被触发时,我需要将这个类名SubCategory 作为参数发送到Products 控制器中的IsSubCategoryExist 方法。可以实现吗?
更新:
控制器代码:
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");
}
}
【问题讨论】:
标签: c# asp.net-mvc