R K
R K

Reputation: 133

Send Parameter on Remote attribute in MVC

Is there a way to send a parameter (not field name) from a Model class to Controller using Remote attribute.

For example, I've this Model class:

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

I need to send this class name SubCategory as a parameter to IsSubCategoryExist method in the Products controller when Remote is triggered. Can it be achieved?

Update:

Controller code:

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

Upvotes: 3

Views: 1549

Answers (2)

TanvirArjel
TanvirArjel

Reputation: 32099

Along with doing following:

public string ClassName { get {return "SubCategory";} }

[Remote("IsSubCategoryExist", "Products", AdditionalFields = "ID, ClassName",
        ErrorMessage = "Product name already exists")]
public string Name { get; set; }

You have to put an hidden field in the form as follows otherwise it will give ClassName is undefined error:

Html.HiddenFor(x => x.ClassName)

Upvotes: 1

Andrei
Andrei

Reputation: 56716

I suppose you could add a field to your model with a static value, and then add it to AdditionalFields:

public string ClassName { get {return "SubCategory";} }

[Remote("IsSubCategoryExist", "Products", AdditionalFields = "ID, ClassName",
        ErrorMessage = "Product name already exists")]
public virtual string Name { get; set; }

Upvotes: 2

Related Questions