In ASP. NET MVC4, add, delete, modify, and query the same page. No pop-up box 01, Repository setup, mvc4repository

Source: Internet
Author: User

In ASP. NET MVC4, add, delete, modify, and query the same page. No pop-up box 01, Repository setup, mvc4repository

Generally, adding, deleting, modifying, and querying are implemented on the same page asynchronously through the pop-up box, which is good. However, sometimes we do not want a dialog box to pop up on the page.KnockoutjsIt can add, delete, modify, and query on the same page in MVVM mode, supplementedknockout.validation.jsYou can also verify the Model. Howeverknockout.validation.jsAndASP.NET MVCThe verification is not seamless and cannot form a consistent and unified verification solution from the client to the server. About Using ASP. NET MVCKnockoutjsAndknockout.validation.jsDo you have any good cases?


So, suddenly looking back,jQueryIn the dark of the lights, I firmly said:ASP.NET MVCIt has been a long time for the joint venture. It is not a matter of client verification and server verification! I want to make it like this:

 

Only the data list and search conditions are displayed:

 

When you click "add", the Add area appears at the top of the list and search areas:

 

When you click "modify", the "modify" area appears at the top of the list and search areas:


Repository Construction

 

Create a simple domain model in the Models folder.

namespace MvcApplication3.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }  
    }
}

 

Use EF Code First to create initial database data. First, it is derived fromDbContext.

using System.Data.Entity;
namespace MvcApplication3.Models
{
    public class ProductContext : DbContext
    {
        public ProductContext() : base("conn")
        {
            Database.SetInitializer(new ProductInitializer());
        }
        public DbSet<Product> Products { get; set; }
    }
}

 

Database Data is initialized inProductInitializerClass.

using System.Data.Entity;
namespace MvcApplication3.Models
{
    public class ProductInitializer : DropCreateDatabaseIfModelChanges<ProductContext>
    {
        protected override void Seed(ProductContext context)
        {
Context. Products. Add (new Product () {Name = "", Price = 85 M, Category = "Prose "});
Context. Products. Add (new Product () {Name = "", Price = 95 M, Category = ""});
Context. Products. Add (new Product () {Name = "Spring blossom", Price = 105 M, Category = "Prose "});
        }
    }
}

 

Configure the EF connection string in Web. config.

  <connectionStrings>
    ......
<Add name = "conn" connectionString = "Data Source = .; user = username; Password = Password; Initial Catalog = ProductStore; Integrated Security = True "providerName =" System. data. sqlClient "/>
  </connectionStrings>

 

The warehousing layer requires an interface first.

using System.Collections.Generic;
namespace MvcApplication3.Models
{
    public interface IProductRepository
    {
IEnumerable <Product> GetAll (); // get all
IEnumerable <Product> LoadProductPageData (ProductParam p, out int total); // obtain paging data
Product GetById (int id); // get it by id. It is usually used when the Update page is displayed.
Product Add (Product item); // Add
Product Update (Product item); // Update
Bool Delete (int id); // Delete
Int DeleteBatch (string [] ids); // batch Delete
    }
} 

 

The implementation of the warehousing interface is based on EF context.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace MvcApplication3.Models
{
    public class ProductRepository : IProductRepository
    {
        private ProductContext db = new ProductContext();
        /// <summary>
/// Get all
        /// </summary>
        /// <returns></returns>
        public System.Collections.Generic.IEnumerable<Product> GetAll()
        {
            return db.Products;
        }
        /// <summary>
/// Retrieve paging data
        /// </summary>
/// <Param name = "para"> query parameters, including PageInde, PageSize, Product-related Name, Category </param>
/// <Param name = "total"> total number of records filtered by query conditions </param>
        /// <returns></returns>
        public IEnumerable<Product> LoadProductPageData(ProductParam para, out int total)
        {
            var products = db.Products.AsEnumerable();
            if (!string.IsNullOrEmpty(para.Name))
            {
                products = products.Where(p => p.Name.Contains(para.Name));
            }
            if (!string.IsNullOrEmpty(para.Category))
            {
                products = products.Where(p => p.Category.Contains(para.Category));
            }
            total = products.Count();
            IEnumerable<Product> result = products
                .OrderByDescending(x => x.Id)
                .Skip(para.PageSize * (para.PageIndex - 1))
                .Take(para.PageSize);
            return result;
        }
        /// <summary>
/// Obtain by Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Product GetById(int id)
        {
            return db.Products.Find(id);
        }
        /// <summary>
/// Add
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Product Add(Product item)
        {
            db.Products.Add(item);
            db.SaveChanges();
            return item;
        }
        /// <summary>
/// Update
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Product Update(Product item)
        {
            try
            {
                if (item == null)
                {
Throw new ArgumentException ("Product cannot be null ");
                }
                var entry = db.Entry(item);
                if (entry.State == EntityState.Detached)
                {
                    var set = db.Set<Product>();
                    Product attachedProduct = set.Local.SingleOrDefault(p => p.Id == item.Id);
// If context tracing has been performed
                    if (attachedProduct != null)
                    {
                        var attachedEntry = db.Entry(attachedProduct);
                        attachedEntry.CurrentValues.SetValues(item);
                    }
Else // if not in the current context
                    {
                        entry.State = EntityState.Modified;
                    }
                }
                db.SaveChanges();
                return item;
            }
            catch (Exception)
            {              
                throw;
            }
        }
        /// <summary>
/// Delete
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            Product product = db.Products.Find(id);
            db.Products.Remove(product);
            if (db.SaveChanges() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
/// Batch Delete
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteBatch(string[] ids)
        {
            foreach (string id in ids)
            {
                Delete(int.Parse(id));
            }
            return -1;
        }
        
    }
}

Which of the above is worth noting?UpdateTo avoid reporting that an object with the same key already exists in ObjectStateManager. ObjectStateManager cannot trace multiple objects with the same key. "error because two objects with the same key are not allowed in the upper and lower sections of EF. During update, we need to determine whether the object to be updated has been tracked by the current context.


Of course, in a three-tier architecture, we can useCallContextThe thread slot obtains the unique EF context instance in the current thread. For more information, see "MVC project practices, SportsStore-01, EF Code First modeling, DAL layer, etc. in a three-tier architecture ".

 

Next, enter the interface design for adding, deleting, modifying, and querying.


ASPNET MVC2 is used as an example for simple addition, deletion, modification, and query. Generally, the query page is also used, but the query page cannot be supplemented.

High score ...... where is the score?

The key point is to submit the query parameters together with the page number when submitting the page... try to hide the domain. Use ViewModel.

In aspnet, how does one add, delete, modify, and query databases without using controls?

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Data. SqlClient;
Using System. Data;

// First, we need to introduce two namespaces: System. Data. sqlClient and System. Data, which have database operation classes.

Namespace ado
{
Class Program
{
Static void Main (string [] args)
{

// Since you want to operate the database, you must first connect to the database. How to connect? First, construct the connection string;

// Different connection methods are available for different databases. For the same database, there are actually different connection strings;

// We construct the simplest string below. This is verified as an SQL server. I don't need to talk about the specific meaning.
String connectionString = "Server = Server name; DataBase = DataBase name; uid = user ID; pwd = User Password ";

// The following is a simple SQL statement used to test database operations;
String selectString = "Select * from userInfo Where name Like '% er '";

// Establish the connection database object Sqlconnection. The constructor is used to pass the connection string. You can also set the connection string using the ConnectionString attribute of conn.
SqlConnection conn = new SqlConnection (connectionString );
Try
{
Conn. Open (); // Open the database connection

If (conn. State = ConnectionState. Open) // judge the status of the current connection object
{
Console. WriteLine ("database connected successfully! ");

// We define a sqlcommand object used to operate the database. Two parameters must be passed to this object. That is, the connection object and the SQL statement string

SqlCommand cmd = new SqlCommand ();
Cmd. Connection = conn;
Cmd. CommandText = selectString;

// The SqlCommand object has four execution database control functions: ExecuteNonQuery ExecuteReader ExecuteScalar ExecuteXmlReader

// Here we use ExecuteReader to return a SqlDataReader. You can check the MSDN
SqlDataReader reader = null;
... The remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.