Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3764
  • Last Modified:

MVC - Controller - Check If A Record Exists Before inserting - Call a method....

I'm new to MVC and .net could someone show me how to write a controller that call a method to check if a record exist before calling a view on a post....
0
yguyon28
Asked:
yguyon28
1 Solution
 
käµfm³d 👽Commented:
Which version of MVC are you using?
0
 
yguyon28Author Commented:
im using mvc 5
0
 
Fernando SotoRetiredCommented:
If you are using Entity Framework to query the database you can build a query to get the records and then check to see if you have any results. For example lets say you have the Northwind database and are looking for a customer record.

// The customer you are looking for.
string customerToFind = "ALFKI";
// Query the database
using(var db = new NorthwindEntities())
{
	  // Find the customer you are looking for.
    var results = (from c in db.Customers
                   where c.CustomerID == customerToFind
                   select c).SingleOrDefault();

    // Test to see if the customer was found
    if( results != null )
    {
        // The record was found so do what you need here
        Console.WriteLine("You have the customer record that you are looking for.");
    }
    else
    {
        // The customer record was NOT found, Do whatever you need if the record was not found.
        Console.WriteLine("Customer NOT found");
    }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now