ASP.NET MVC (Fatura Kayıtları) - Veri Modelleri

  • 782
  • (1)
  • (5)
  • 05 Şub 2018

InvoicesWeb projesi içerisinde MS-SQL' den InvoicesDB veritabanına ait tanımlanmış prosedürleri çalıştıracak ve bilgi çekebilecek veri modelleri tanımlayabilirsiniz. Bu veri modellerini doğrudan tabloların şemalarıyla özdeş olarak Entity Framework ile oluşturabilirsiniz. Ancak bu içerikte bu proje için daha temel bir teknik olan ADO.NET kullanılacaktır. Daha sonraki içeriklerde Entity Framework ile geliştirebilir projelere de mutlaka değinilecektir.

Veritabanı Bağlantısı

Veritabanı bağlantısı için Web.config dosyasında bir adet ConnectionString oluşturabilirsiniz. Her bağlantı işleminde bu bağlantı metnini çağıracağınız için, eğer sonradan değişirse tek bir yerden değiştirmeniz daha kolay olacaktır.

Web.config dosyasında configuration içerisinde connectionStrings isimli bir öğe oluşturarak bağlantı metnini yazabilirsiniz.


<configuration>
  <connectionStrings>
    <add name="ConnString" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=InvoicesDB; Integrated Security=True;"/>
  </connectionStrings>
...
...
...
</configuration>

Models dizini içerisinde IProcedure isimli bir interface oluşturup bütün veri modellerinde kullanarak ortak metotları kullanabilirsiniz.


interface IProcedure
{
    SqlCommand ToCreateCommand(SqlConnection connection);
    SqlCommand ToUpdateCommand(SqlConnection connection);
    SqlCommand ToDeleteCommand(SqlConnection connection);
}

Bu üç metot bütün veri modellerinde mevcut olacağı için, her veritabanı bağlantısında ayrı class üzerinden değil tek bir interface üzerinden bu metotları çağırabilirsiniz.

Veritabanı işlemleri için bir katman oluşturup genel bütün metotları burada tanımlayabilirsiniz. Proje içerisinde Helpers isimli bir dizin oluşturabilirsiniz. Solution Explorer üzerinde proje adına (InvoiceWeb) sağ tıklayıp Add menüsünden New Folder ile yeni dizin oluşturup adını Helpers olarak girin.

Bu dizine de sağ tıklayıp Add menüsünden Class tuşuna tıklayıp DBHelper isimli yeni bir sınıf oluşturun.


public class DBHelper
{
    // Bağlantı metni
    private string ConnectionString { get { return System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; } }

    // Veritabanına bağlanıp, SqlConnection türünde bağlantı nesnesini döndüren metot
    private async Task<SqlConnection> OpenConnection()
    {
        SqlConnection connection = new SqlConnection(ConnectionString);
        await connection.OpenAsync();
        return connection;
    }

    // Bağlantıyı kapatma metodu
    private void CloseConnection(SqlConnection connection)
    {
        connection.Close(); connection.Close();
    }

    // IProcedure arabirimi olan her veri türü için oluşturma prosedürü çalıştıran metot
    public async Task<DBResult> CreateProcedure(IProcedure procedure)
    {
        var connection = await OpenConnection(); // bağlantı açılır
        var command = procedure.ToCreateCommand(connection); // müşteri, fatura veya fatura satırı oluşturma prosedürü için komut oluşturur
        var dataReader = await command.ExecuteReaderAsync(); // komutu çalıştırıp SqlDataReader nesnesine geri dönüş yapar
        DBResult result = new DBResult(); // geri dönüş için DBResult türünde tanımlı veri
        await result.GetFromDataReader(dataReader); // prosedürün sonucu okunur
        CloseConnection(connection); // bağlantı kapanır
        return result; // result nesnesi metodun dönüş değeridir
    }

    // IProcedure arabirimi olan her veri türü için güncelleme prosedürü çalıştıran metot
    public async Task<DBResult> UpdateProcedure(IProcedure procedure)
    {
        var connection = await OpenConnection();
        var command = procedure.ToUpdateCommand(connection);
        var dataReader = await command.ExecuteReaderAsync();
        DBResult result = new DBResult();
        await result.GetFromDataReader(dataReader);
        CloseConnection(connection);
        return result;
    }

    // IProcedure arabirimi olan her veri türü için silme prosedürü çalıştıran metot
    public async Task<DBResult> DeleteProcedure(IProcedure procedure)
    {
        var connection = await OpenConnection();
        var command = procedure.ToDeleteCommand(connection);
        var dataReader = await command.ExecuteReaderAsync();
        DBResult result = new DBResult();
        await result.GetFromDataReader(dataReader);
        CloseConnection(connection);
        return result;
    }

    /* Müşteri oluşturma veya düzenleme sayfalarında müşteri durum ve 
       türü seçebilmek için bu değerlerin veritabanından çekilmesi gereklidir */
    public async Task<CustomerValuesModel> GetCustomerValues()
    {
        var connection = await OpenConnection();
        var command = new SqlCommand("select * from tblCustomerTypes select * from tblCustomerStatuses", connection);
        var dataReader = await command.ExecuteReaderAsync();
        List<CustomerTypeModel> customerTypes = new List<CustomerTypeModel>();
        while (await dataReader.ReadAsync())
        {
            CustomerTypeModel customerType = new CustomerTypeModel();
            customerType.GetFromDataReader(dataReader);
            customerTypes.Add(customerType);
        }
        await dataReader.NextResultAsync();
        List<CustomerStatusModel> customerStatuses = new List<CustomerStatusModel>();
        while (await dataReader.ReadAsync())
        {
            CustomerStatusModel customerStatus = new CustomerStatusModel();
            customerStatus.GetFromDataReader(dataReader);
            customerStatuses.Add(customerStatus);
        }
        CloseConnection(connection);
        return new CustomerValuesModel() { CustomerTypes = customerTypes, CustomerStatuses = customerStatuses };
    }
}

Models Dizini

Solution Explorer üzerinde Models dizini içerisinde yeni sınıflar oluşturarak bu sınıflarla veritabanına bağlantı sağlayıp bilgi alışverişinde bulunulabilir. Örneğin Fatura Kayıtları (InvoicesWeb) projesi için Veritabanı içeriğinde çok sayıda prosedür yazılmıştı. Bunlardan müşteri kayıtları ile ilgili olan prosedürleri kullanarak başlayabilirsiniz.

dbo.procCreateCustomer prosedürü ile müşteri oluşturmak, dbo.procUpdateCustomer prosedürü ile müşteri bilgileri güncellemek, dbo.procDeleteCustomer prosedürü ile de müşteriyi silmek mümkündür.

Müşteri Veri Modeli

Models dizinine sağ tıklayıp Add menüsünden Class tuşuna tıklayın. Karşınıza gelecek ekrandan yeni bir class oluşturabileceğiniz dosyanın adını girip menüden Class seçeneğinin seçili olduğundan da emin olun. Class ismi olarak CustomerModel ismini girin. Ardından sınıf modeli oluşturulacaktır.

Veri modelini aşağıdaki gibi kodlayabilirsiniz. CustomerModel sınıfına IProcedure arabirimini uygulamalısınız.


public class CustomerModel: IProcedure
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public int CustomerTypeId { get; set; }
    public string CustomerType { get; private set; }
    public int CustomerStatusId { get; set; }
    public string CustomerStatus { get; private set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string TaxNumber { get; set; }
    public string Address { get; set; }
    public DateTime Register { get; set; }

    // SqlDataReader ile sorgu okunurken bu metot ile veriler alınacak
    public void GetFromDataReader(SqlDataReader dataReader)
    {
        CustomerId = Convert.ToInt32(dataReader["colCustomerId"]);
        Name = dataReader["colName"].ToString();
        CustomerType = dataReader["colCustomerType"].ToString();
        CustomerStatus = dataReader["colCustomerStatus"].ToString();
        Email = dataReader["colEmail"].ToString();
        Phone = dataReader["colPhone"].ToString();
        TaxNumber = dataReader["colTaxNumber"].ToString();
        Address = dataReader["colAddress"].ToString();
        Register = Convert.ToDateTime(dataReader["colRegister"]);
    }

    public SqlCommand ToCreateCommand(SqlConnection connection)
    {
        // SqlCommand ile prosedür çalıştıracağımız için CommandType değeri StoredProcedure olmalı
        SqlCommand command = new SqlCommand("dbo.procCreateCustomer", connection)
            { CommandType = System.Data.CommandType.StoredProcedure };
        // Parametreler
        //@_name nvarchar(128), @_customerTypeID int, @_customerStatusID int, @_email varchar(64)
        //@_phone varchar(32), @_taxNumber varchar(32), @_address nvarchar(256)
        command.Parameters.AddRange(new SqlParameter[] { PrmName, PrmCustomerTypeId, PrmCustomerStatusId,
            PrmEmail, PrmPhone, PrmTaxNumber, PrmAddress });
        return command;
    }

    public SqlCommand ToUpdateCommand(SqlConnection connection)
    {
        // SqlCommand ile prosedür çalıştıracağımız için CommandType değeri StoredProcedure olmalı
        SqlCommand command = new SqlCommand("dbo.procUpdateCustomer", connection)
        { CommandType = System.Data.CommandType.StoredProcedure };
        // Parametreler
        //@_name nvarchar(128), @_customerTypeID int, @_customerStatusID int, @_email varchar(64)
        //@_phone varchar(32), @_taxNumber varchar(32), @_address nvarchar(256)
        command.Parameters.AddRange(new SqlParameter[] { PrmCustomerId, PrmName, PrmCustomerTypeId, PrmCustomerStatusId,
            PrmEmail, PrmPhone, PrmTaxNumber, PrmAddress });
        return command;
    }

    public SqlCommand ToDeleteCommand(SqlConnection connection)
    {
        // SqlCommand ile prosedür çalıştıracağımız için CommandType değeri StoredProcedure olmalı
        SqlCommand command = new SqlCommand("dbo.procDeleteCustomer", connection)
        { CommandType = System.Data.CommandType.StoredProcedure };
        // Parametreler
        //@_customerId int
        command.Parameters.AddRange(new SqlParameter[] { PrmCustomerId });
        return command;
    }

    // Aşağıda sadece get metodu ile enkapsüle edilmiş özellikler tanımlandı
    // bu özellikler SqlCommand nesneleri için parametre olarak kullanılacak
    private SqlParameter PrmCustomerId { get { return new SqlParameter("@_customerId", System.Data.SqlDbType.Int) { Value = CustomerId }; } }
    private SqlParameter PrmName { get { return new SqlParameter("@_name", System.Data.SqlDbType.NVarChar, 128) { Value = Name }; } }
    private SqlParameter PrmCustomerTypeId { get { return new SqlParameter("@_customerTypeID", System.Data.SqlDbType.Int) { Value = CustomerTypeId }; } }
    private SqlParameter PrmCustomerStatusId { get { return new SqlParameter("@_customerStatusID", System.Data.SqlDbType.Int) { Value = CustomerStatusId }; } }
    private SqlParameter PrmEmail { get { return new SqlParameter("@_email", System.Data.SqlDbType.VarChar, 64) { Value = Email }; } }
    private SqlParameter PrmPhone { get { return new SqlParameter("@_phone", System.Data.SqlDbType.VarChar, 32) { Value = Phone }; } }
    private SqlParameter PrmTaxNumber { get { return new SqlParameter("@_taxNumber", System.Data.SqlDbType.VarChar, 32) { Value = TaxNumber }; } }
    private SqlParameter PrmAddress { get { return new SqlParameter("@_address", System.Data.SqlDbType.NVarChar, 256) { Value = Address }; } }
}

Veri modelinde, veritabanındaki ilgili tabloya (tblCustomers) ve ilgili prosedürlere karşılık gelen özellikler belirlenir.

GetFromDataReader metodu müşteriler okunurken çalıştırılacak, ToCreateCommand müşteri oluşturma formundan okunan bilgileri kullanacak, ToUpdateCommand müşteri güncelleme formundan okunan bilgileri kullanacak.

CustomerModel sınıfının bittiği yerde hemen altına aşağıdaki sınıfları tanımlayın. CustomerTypeModel ve CustomerStatusModel sınıfları ile müşteri türleri ve durumları liste halinde müşteri oluşturma formuna aktarılıp DropDownList içerisinde gösterilecek. Böylelikle müşteri oluştururken kullanıcı bu değerlerden birini seçebilecek.


// Müşteri türlerinin veri modeli
public class CustomerTypeModel
{
    public int Id { get; set; }
    public string Value { get; set; }

    // Veritabanından tek satır okuma işlemi
    public void GetFromDataReader(SqlDataReader dataReader)
    {
        Id = Convert.ToInt32(dataReader["colCustomerTypeID"]);
        Value = dataReader["colCustomerType"].ToString();
    }
}

// Müşteri durumlarının veri modeli
public class CustomerStatusModel
{
    public int Id { get; set; }
    public string Value { get; set; }

    // Veritabanından tek satır okuma işlemi
    public void GetFromDataReader(SqlDataReader dataReader)
    {
        Id = Convert.ToInt32(dataReader["colCustomerStatusID"]);
        Value = dataReader["colCustomerStatus"].ToString();
    }
}

// İki veri türü aynı sayfada olacağı için tek bir veri türünde birleştirmek faydalı olacaktır
public class CustomerValuesModel
{
    public List<CustomerTypeModel> CustomerTypes { get; set; }
    public List<CustomerStatusModel> CustomerStatuses { get; set; }

    public CustomerValuesModel() { CustomerTypes = new List<CustomerTypeModel>(); CustomerStatuses = new List<CustomerStatusModel>(); }
}

Controller Oluşturma

Controllers dizini içerisinde CustomerController isimli bir MVC Controller oluşturun. İçerisinde oluşturacağımız Action metotları asenkronize olacaktır. Böylelikle program aynı anda birden fazla işlemi çalıştırabilir.


public class CustomerController : Controller
{
    // Sayfa ilk açıldığında çalışacak metot budur
    public async Task<ActionResult> Create()
    {
        DBHelper db = new DBHelper();
        ViewBag.CustomerValues = await db.GetCustomerValues();
        return View();
    }
    
    // Sayfadaki form doldurulup gönderildiğinde çalışacak metot budur
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(CustomerModel customer)
    {
        DBHelper db = new DBHelper();
        ViewBag.CustomerValues = await db.GetCustomerValues();
        var result = await db.CreateProcedure(customer);
        if (result.Success) ModelState.Clear();
        ViewBag.Result = result;
        return View();
    }
}

ValidateAntiForgeryToken isimli attribute isteğin başka bir uygulamadan gönderilmesini engeller. View üzerindeki formda da @Html.ValidationSummary(true, "", new { @class = "text-danger" }) satırı sayesinde Action metodu ile üretilen token, web sayfasındaki token ile eşleştirilerek işlem yapılır.

Create ismine sağ tıklayıp Add View tuşuna basarak action metodu için View ekleyebilirsiniz.

Herhangi bir model seçmeksizin ekleyebilir veya Empty seçeneği yerine Create seçeneği ile model olarak InvoicesWeb.Models.CustomerModel veri türünü seçip de oluşturabilirsiniz.


@model InvoicesWeb.Models.CustomerModel

@{
    ViewBag.Title = "Müşteri Oluştur";
    InvoicesWeb.Models.CustomerValuesModel customerValues = ViewBag.CustomerValues;
    List<SelectListItem> listCustomerTypes = new List<SelectListItem>();
    foreach (var type in customerValues.CustomerTypes)
    {
        listCustomerTypes.Add(new SelectListItem() { Text = type.Value, Value = type.Id.ToString() });
    }
    List<SelectListItem> listCustomerStatuses = new List<SelectListItem>();
    foreach (var type in customerValues.CustomerStatuses)
    {
        listCustomerStatuses.Add(new SelectListItem() { Text = type.Value, Value = type.Id.ToString() });
    }
    InvoicesWeb.Helpers.DBResult result = ViewBag.Result;
}

<h2>Müşteri Oluştur</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CustomerTypeId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CustomerTypeId, listCustomerTypes, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CustomerTypeId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CustomerStatusId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CustomerStatusId, listCustomerStatuses, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CustomerStatusId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TaxNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TaxNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TaxNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Oluştur" class="btn btn-default" />
                @if (result != null)
                {
                    <span class="text-@(result.Success ? "success" : "danger")">@result.Result</span>
                }
            </div>
        </div>
    </div>
}
<div>
    <a href="@Url.Action("List", "Customer")">Listeye Dön</a>
</div>

Müşteri oluşturmak için kullanılacak formun View içeriği yukarıdaki gibidir. Ancak uygulamayı çalıştırıp http://localhost:xxxxx/Customer/Create sayfasına girdiğinizde aşağıdaki gibi bir görüntü ile karşılaşacaksınız.

Formdaki @Html.LabelFor metotları CustomerModel nesnesinin doğrudan özellik adını getirecektir. Bunun yerine doğrudan label tagı oluşturabilirsiniz. Veya @Html.LabelFor(model => model.Name, "Müşteri Adı", htmlAttributes: new { @class = "control-label col-md-2" }) şeklinde fazladan parametre ile görünmesini istediğiniz ismi yazabilirsiniz. Ya da CustomerModel sınıfının özelliklerine Display isminde bir attribute ekleyebilirsiniz.


public class CustomerModel: IProcedure
{
    [Display(Name = "Müşteri Adı")]
    public string Name { get; set; }
    [Display(Name = "Müşteri Türü")]
    public int CustomerTypeId { get; set; }
    [Display(Name = "Müşteri Türü")]
    public string CustomerType { get; private set; }
    [Display(Name = "Müşteri Durumu")]
    public int CustomerStatusId { get; set; }
    [Display(Name = "Müşteri Durumu")]
    public string CustomerStatus { get; private set; }
    [Display(Name = "E-Posta")]
    public string Email { get; set; }
    [Display(Name = "Telefon")]
    public string Phone { get; set; }
    [Display(Name = "Vergi Numarası")]
    public string TaxNumber { get; set; }
    [Display(Name = "Adres")]
    public string Address { get; set; }
    public DateTime Register { get; set; }
    
    // ...
}

CustomerModel sınıfını yukarıdaki gibi güncellediğinizde görünen etiketler de değişecektir.

Formu doldurup Oluştur tuşuna tıkladığınızda form bilgileri CustomerController içindeki [HttpPost] olarak tanımlanan Create metoduna gönderilecek. Aşağıdaki kodlar çalıştırılacaktır.


DBHelper db = new DBHelper();
// DBHelper nesnesi tanımlanır
ViewBag.CustomerValues = await db.GetCustomerValues();
// Müşteri durumları ve müşteri türleri dropdowna konulmak üzere veritabanından çekilir
var result = await db.CreateProcedure(customer);
// oluşturma prosedürü çalıştırılır
if (result.Success) ModelState.Clear();
// eğer oluşturma başarılı ise View' a ait model yani CustomerModel nesnesi temizlenir
// bu alanların temizlenmesini sağlar
ViewBag.Result = result;
// sonuç bilgisi ViewBag üzerinde Result dynamic değişkenine gönderilir
return View();
//View() metodu ile arayüz geri döndürülür

Form bilgileri gönderilip veritabanındaki prosedür çalıştırılınca girilen veriler tblCustomers tablosuna satır olarak işlenecektir.

Tek bir müşteri kaydını okumak için aşağıdaki metodu CustomerModel sınıfı içerisine ekleyin.


public class CustomerModel: IProcedure
{
    // ...
    
    public SqlCommand ToGetOneCommand(SqlConnection connection)
    {
        // SqlCommand ile tek bir müşteri kaydını almak için uygulanan sorgu
        SqlCommand command = new SqlCommand(@"
            select colCustomerID, colName, c.colCustomerTypeID, c.colCustomerStatusID,
                colCustomerStatus, colCustomerType, colEmail, colPhone, colTaxNumber,
                colAddress, colRegister
            from tblCustomers c
                left join tblCustomerTypes ct on ct.colCustomerTypeID = c.colCustomerTypeID
                left join tblCustomerStatuses cs on cs.colCustomerStatusID = c.colCustomerStatusID
            where colCustomerID = @_customerId", connection);
        command.Parameters.Add(PrmCustomerId);
        return command;
    }
    
    // ...
}

Bu metot sadece gereken SqlCommand nesnesini oluşturacaktır. DBHelper sınıfı içerisinde bu metodu çağıracağınız başka bir metot ekleyin.


public class DBHelper
{
    // ...

    // Tek bir müşteri kaydını almak için
    public async Task<CustomerModel> GetCustomer(int id)
    {
        CustomerModel customer = new CustomerModel() { CustomerId = id };
        var connection = await OpenConnection();
        var command = customer.ToGetOneCommand(connection);
        var dataReader = await command.ExecuteReaderAsync();
        while (await dataReader.ReadAsync())
        {
            customer.GetFromDataReader(dataReader);
        }
        CloseConnection(connection);
        return customer;
    }

    // ...
}

Controller içerisine aşağıdaki metotları da ekleyip diğer işlemleri tamamlayabilirsiniz.


public class CustomerController : Controller
{
    public async Task<ActionResult> List()
    {
        DBHelper db = new DBHelper();
        ViewBag.Customers = await db.ListCustomers();
        return View();
    }

    public async Task<ActionResult> Create()
    {
        DBHelper db = new DBHelper();
        ViewBag.CustomerValues = await db.GetCustomerValues();
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(CustomerModel customer)
    {
        DBHelper db = new DBHelper();
        ViewBag.CustomerValues = await db.GetCustomerValues();
        var result = await db.CreateProcedure(customer);
        if (result.Success) ModelState.Clear();
        ViewBag.Result = result;
        return View();
    }

    public async Task<ActionResult> Edit(int id)
    {
        DBHelper db = new DBHelper();
        var customer = await db.GetCustomer(id);
        ViewBag.Customer = customer;
        ViewBag.CustomerValues = await db.GetCustomerValues();
        return View(customer);
    }

    [HttpPost]
    public async Task<ActionResult> Edit(CustomerModel customer)
    {
        DBHelper db = new DBHelper();
        ViewBag.CustomerValues = await db.GetCustomerValues();
        var result = await db.UpdateProcedure(customer);
        ViewBag.Result = result;
        return View();
    }

    public async Task<ActionResult> Delete(int id)
    {
        DBHelper db = new DBHelper();
        var customer = await db.GetCustomer(id);
        if (customer == null) return RedirectToAction("List", "Customer");
        ViewBag.CustomerName = customer.Name;
        return View(customer);
    }

    [HttpPost, ActionName("Delete")]
    public async Task<ActionResult> DeleteConfirm(int id)
    {
        DBHelper db = new DBHelper();
        CustomerModel customer = new CustomerModel() { CustomerId = id };
        var result = await db.DeleteProcedure(customer);
        return RedirectToAction("List", "Customer");
    }
}

Proje içerisinde CustomerController' a ait Create için View mevcut. Müşterileri listelemek için List, düzenleme işlemleri için Edit, silmek için ise Delete metotlarına birer View oluşturmanız gerekiyor.

Create metoduna oluşturduğunuz gibi bu metotlara da sağ tıklayıp View oluşturun. HttpPost özelliği olan actionlar için view oluşturmayın. Edit.cshtml Viewi aşağıdaki gibi olmalıdır.


@model InvoicesWeb.Models.CustomerModel

@{
    ViewBag.Title = "Müşteri Düzenle";
    InvoicesWeb.Models.CustomerValuesModel customerValues = ViewBag.CustomerValues;
    List<SelectListItem> listCustomerTypes = new List<SelectListItem>();
    foreach (var type in customerValues.CustomerTypes)
    {
        listCustomerTypes.Add(new SelectListItem() { Text = type.Value, Value = type.Id.ToString() });
    }
    List<SelectListItem> listCustomerStatuses = new List<SelectListItem>();
    foreach (var type in customerValues.CustomerStatuses)
    {
        listCustomerStatuses.Add(new SelectListItem() { Text = type.Value, Value = type.Id.ToString() });
    }
    InvoicesWeb.Helpers.DBResult result = ViewBag.Result;
}

<h2>Müşteri Düzenle</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.HiddenFor(model => model.CustomerId)
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CustomerTypeId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CustomerTypeId, listCustomerTypes, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CustomerTypeId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CustomerStatusId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CustomerStatusId, listCustomerStatuses, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CustomerStatusId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TaxNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TaxNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TaxNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Düzenle" class="btn btn-default" />
                @if (result != null)
                {
                    <span class="text-@(result.Success ? "success" : "danger")">@result.Result</span>
                }
            </div>
        </div>
    </div>
}

<div>
    <a href="@Url.Action("List", "Customer")">Listeye Dön</a>
</div>

Delete.cshtml isimli view ise aşağıdaki gibi olacaktır.


@model InvoicesWeb.Models.CustomerModel

@{
    ViewBag.Title = "Müşteri Sil";
}

<h2>Müşteri Sil</h2>

<h3>Müşteri kaydını silmek istediğinize emin misiniz?</h3>
<div>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CustomerType)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CustomerType)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CustomerStatus)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CustomerStatus)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Email)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Email)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Phone)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Phone)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.TaxNumber)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.TaxNumber)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Address)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Address)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Register)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Register)
        </dd>

    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()

        <div class="form-actions no-color">
            <input type="submit" value="Sil" class="btn btn-default" /> |
            @Html.ActionLink("Listeye Dön", "List", "Customer")
        </div>
    }
</div>

İlişkili İçerikler

Fatura kayıtlarının içerisinde tutulacağı ve işleneceği veritabanını MS-SQL üzerinde oluşturabilirsiniz.

ASP.NET MVC ile fatura kayıtlarının tutulduğu, görüntülendiği, güncellendiği bir uygulama oluşturabilirsiniz.

Oturum açmak için sayfa düzenini belirlemek, gönderilen oturum bilgilerinin veritabanında prosedür ile doğrulanması ve yönlendirme işlemleri login sayfasının temel işleyişidir.

Fatura Kayıtları projesinde faturalar ve fatura satırları için de birer controller oluşturup gereken metotları oluşturabilirsiniz.

Paylaşın
Etiket Bulutu