Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Parameter on Remote attribute in MVC

Tags:

c#

asp.net-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");
     }
}
like image 768
R K Avatar asked Jan 22 '26 08:01

R K


2 Answers

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; }
like image 121
Andrei Avatar answered Jan 23 '26 21:01

Andrei


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)
like image 24
TanvirArjel Avatar answered Jan 23 '26 23:01

TanvirArjel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!