c# - 在 MVC 中发送远程属性的参数

标签 c# asp.net-mvc

有没有办法使用 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/

相关文章:

c# - FtpWebRequest ListDirectory 不返回所有文件

javascript - 如何在javascript中动态获取html表格数据值

c# - 为部署进行 web.config 转换的最简单方法?

asp.net - .NET Core 静态文件响应压缩中间件

c# - 使用 MVC 根据枚举值定义 HTML 元素颜色

asp.net-mvc - 使用 Linq to SQL 返回空字符串 - 没有行的相关表 - ASP.Net MVC

c# - 正则表达式替换错误符号 C#

c# - Excel.Workbook.SaveAs(...) 同名文件

asp.net-mvc - 如何检查经过身份验证的用户是常规 ASP.NET Identity 帐户还是链接到外部提供商的帐户

c# - AuthenticationManager.SignIn() 不存在于 AuthenticationManager 类中