logo
down
shadow

Can I use MVC 5 remote validation to check for duplicate values, but exclude the item being edited?


Can I use MVC 5 remote validation to check for duplicate values, but exclude the item being edited?

Content Index :

Can I use MVC 5 remote validation to check for duplicate values, but exclude the item being edited?
Tag : chash , By : CookingCoder
Date : November 28 2020, 04:01 AM

will be helpful for those in need So you will need 2 view models. One for create and one for edit. By passing the item id we know that it is an edit, and if it is not past we know it is a create.
public class CreateItemViewModel
{
    [Remote("IsSerialAvailable", "Value")]
    public string Serial { get; set; }
}

public class EditItemViewModel
{
    [Remote("IsSerialAvailable", "Value", AdditionalFields = "ItemId")]
    public string Serial { get; set; }

    public int ItemId { get; set; }
}

    public ActionResult IsSerialAvailable(string serial, int? itemId = null)
    {
        List<int> t = new List<int>();

        Item item;

        if (itemId.HasValue)
        {
            item = db.Items.SingleOrDefault(i => i.Serial == Serial && i.Id != itemId.Value);

        }
        else
        {
            item = db.Items.SingleOrDefault(i => i.Serial == Serial);
        }

        if (item != null)
        {
            return Json(false, JsonRequestBehavior.AllowGet);
        }

        return Json(true, JsonRequestBehavior.AllowGet);
    }

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

MVC 3 Remote Validation, problem with duplicate check in Edit view


Tag : asp.net-mvc-3 , By : barefootChild
Date : March 29 2020, 07:55 AM
Does that help You should use view models. Those are classes which are specifically designed to meet the requirements of a view. Controller actions should take/pass only view models to views and never your domain models. So you will have two controller actions, one for inserting and one for editing, and two corresponding view models with their respective validation rules.

How to check if any item is being edited in the QTreeView or not?


Tag : cpp , By : Jay Crockett
Date : March 29 2020, 07:55 AM
This might help you you can check the view's internal state to see if it is in editing state
if (my_treeview->state() != QAbstractItemView::EditingState)
{
   /* do some stuff */
}

Check current Item Id against remote validation MVC


Tag : chash , By : Kenny
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You need to use AdditionalFields of RemoteAttribute and use the Id (Primary key) of that table.
[Remote("DepartmentNameExists", "Department", "Department Name is already taken.", AdditionalFields = "Id")]
public string Name { get; set; }
public JsonResult DepartmentNameExists(string name, int id = 0)
{
    return db.Departments.Any(x => x.Name == name.Trim() && x.Id != id) 
              ? Json(string.Format("{0} already exists.", name), 
                                        JsonRequestBehavior.AllowGet)
              : Json(true, JsonRequestBehavior.AllowGet);
}

How can I check the inserted/edited item in jsgrid isn't duplicate?


Tag : javascript , By : Chandra P Singh
Date : March 29 2020, 07:55 AM
Does that help The reason is that validate supports only synchronous validation, and validation from our example requires ajax call, so it's asynchronous.
You have two options:

Custom ValidationAttribute: How to check for duplicate value, ignoring the object being edited


Tag : asp.net , By : Mike
Date : March 29 2020, 07:55 AM
wish of those help The item which is currently being edited most likely has some kind of property to identify it (look it up in the database). Therefore, you need to get that property so you can exclude that when you are searching the database for duplicate tags. Here is how to do that in your custom validation class. I am making the assumption the identifier is named TrainerId:
public class UrlTagValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        string tag = value as string;
        if(string.IsNullOrWhiteSpace(tag))
            return new ValidationResult("URL Tag is required.");

        var currentTrainer = validationContext.ObjectInstance 
                                 as TrainerModel;
        if (currentTrainer == null)
        {
            // What do you want to do? You cannot always return an error
            // because another type could be using this custom validation.
            // Or you can return an error. Depends on your requirements and 
            // and usage.
        }
        using(var dbContext = new OnBoard101Entities())
        {
            if(dbContext.TrainerDetails.Any(td => td.Tag == tag && td.TrainerId != 
                                            currentTrainer.TrainerId))
            {
                return new ValidationResult("This URL Tag is not available. Please enter a different one.");
            }
        }

        return ValidationResult.Success;
    }
}
Related Posts Related QUESTIONS :
  • What is the difference between String and string in C#?
  • Multicore Text File Parsing
  • Invalid Resource File
  • Getting DirectoryNotFoundException when trying to Connect to Device with CoreCon API
  • How to wait for thread complete before continuing?
  • Is String.Format as efficient as StringBuilder
  • ASP.NET Web Service Results, Proxy Classes and Type Conversion
  • sgen.exe fails during build
  • In C#, why can't a List<string> object be stored in a List<object> variable
  • C# loop - break vs. continue
  • How to access .Net element on Master page from a Content page?
  • Why are unsigned int's not CLS compliant?
  • Why is Array.Length an int, and not an uint
  • How do I make event callbacks into my win forms thread safe?
  • Genealogy Tree Control
  • WCF Service - Backward compatibility issue
  • Binary patch-generation in C#
  • Tab Escape Character?
  • When do Request.Params and Request.Form differ?
  • The imported project "C:\Microsoft.CSharp.targets" was not found
  • Numeric Data Entry in WPF
  • Print a Winform/visual element
  • C# logic order and compiler behavior
  • When to use an extension method with lambda over LINQtoObjects to filter a collection?
  • How to make a button appear as if it is pressed?
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com