Solved

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

Posted on 2014-02-21
3
2,926 Views
Last Modified: 2014-03-03
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
Comment
Question by:yguyon28
3 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39878745
Which version of MVC are you using?
0
 

Author Comment

by:yguyon28
ID: 39878767
im using mvc 5
0
 
LVL 63

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 39879363
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question