Azure Mobile Services–Menambahkan Script pada proses CRUD

Tutorial sebelumnya dapat dilihat pada tautan berikut: https://erickkurniawan.net/2015/12/19/azure-mobile-servicesmengupdate-data/

Anda juga dapat menambahkan script untuk mengubah atau memfilter data sebelum atau sesudah perintah CRUD dijalankan. Dengan script anda dapat bekerja dengan bermacam-macam objek data sebagai berikut :

  • Request : execute default operation
  • Query : filtering, paging, ordering
  • Table : CRUD operation dan query
  • MSSQL : Direct SQL Statement

Untuk mencoba menggunakan script ikuti langkah berikut :

Pada services yang sebelumnya anda buat buka menu DATA. Kemudian pilih table TodoItem.

image

Kemudian pilih menu SCRIPT, anda dapat menambahkan script ketika operasi insert, update, delete,dan read.

image

Disini perintah script yang dijalankan menggunakan nodejs, Sebagai contoh pada script tambahkan kode berikut :

image

Kemudian tekan Save, dan jalankan aplikasi TodoItem. Tambahkan record baru kedalam aplikasi anda.

image

Setelah anda tambahkan, coba lihat menu log untuk melihat log yang dituliskan ketika perintah insert dijalankan.

image

Maka anda dapat melihat log yang kita create ketika perintah insert di table TodoItem dijalankan.

image

Jika anda sudah menginstall azure cli maka anda juga dapat menggunakan command prompt untuk melihat list daftar mobile services dan script yang sudah anda buat.

image

image

Menambahkan Field baru dengan Script

Jika konfigurasi dynamic schema diaktifkan, maka kita akan dapat menambahkan field pada table secara dinamis (menggunakan script). Cara ini mirip dengan penggunaan entity framework code first.

image

Pada contoh dibawah ini akan ditunjukan bagaimana cara untuk menambahkkan field ‘DateCourseCreated’ secara dinamis dan menambahkan nilai kedalam field tersebut saat perintah insert dijalankan.

image

Menambahkan Field baru dengan Script

Jika konfigurasi dynamic schema diaktifkan, maka kita akan dapat menambahkan field pada table secara dinamis (menggunakan script). Cara ini mirip dengan penggunaan entity framework code first.

image

Pada contoh dibawah ini akan ditunjukan bagaimana cara untuk menambahkkan field ‘DateCourseCreated’ secara dinamis dan menambahkan nilai kedalam field tersebut saat perintah insert dijalankan.

image

Buka fiddler, kemudian tambahkan data baru kedalam table Courses.

image

Seletah itu jalankan method GET untuk melihat output JSON yang dikirimkan.

image

Dapat anda lihat bahwa disetiap record akan ada satu field baru dengan nama ‘DateCourseCreated’. Jika anda lihat pada struktur table, maka field tersebut juga sudah ditambahkan secara permanen.

image

 

Menggunakan Query Object pada SCRIPT

Anda juga dapat memanipulasi objek Query dengan menggunakan SCRIPT. Pada contoh dibawah ini akan ditunjukan bagaimana cara memanipulasi objek query.

image_thumb

Setelah script diatas disimpan, coba jalankan method GET untuk request data dengan menggunakan fiddler. Maka hasil output setelah objek query dimanipulasi adalah sebagai berikut:

image_thumb[1]

Dapat dilihat pada output bahwa data yang ditampilkan adalah data yang field ‘complete’ bernilai ‘false’.

Advertisement

Cara Migrasi Database dari SQL Server ke SQL Azure

Pada tutorial kali ini akan dibahas bagaimana cara melakukan migrasi dari SQL Server database ke SQL Azure. Langkah pertama yang harus dilakukan adalah instalasi SQL Database Migration Wizard pada tautan berikut.

image

Sebagai contoh pada tutorial kali ini kita akan mengeksport database dengan nama StorageDb ke SQL Azure.

 image

Caranya cukup mudah, pertama masuk kedalam portal Azure anda di halaman http://portal.azure.com. Kemudian buat SQL Azure dengan cara klik pada SQL Databases, kemudian pilih Add, kemudian masukan nama database yang akan dibuat sebagai contoh StorageDb, pada konfigurasi server tambahkan server baru karena kita belum membuat server sebelumnya.

image

Untuk paket kita akan mencoba paket yang paling murah yaitu paket basic seharga 7orb-an per bulan. Untuk pilihan region, anda dapat memilih region yang paling dekat dengan lokasi target pengguna anda.

image

Untuk group, anda dapat menambahkan group baru jika belum memiliki group. Group digunakan untuk mengelompokan resource yang anda buat pada layanan Microsoft Azure.

image

Langkah terakhir tekan tombol Create. Setelah beberapa saat anda akan melihat bahwa database pada SQL Azure sudah berhasil dibuat.

image

image

Setelah database di SQL Azure siap, maka langkah selanjutnya adalah menggunakan tools SQL Database Migration Wizard.  

Sebelumnya anda dapat menambahkan konfigurasi firewall pada SQL Azure agar komputer anda dapat terkoneksi kedalam layanan SQL Azure, ikuti langkah dibawah ini.

image

Kemudian tambahkan ip dari komputer anda pada daftar tersebut agar anda dapat mengakses layanan SQL Azure dari komputer anda.

image

Buka SQL Database Migration Wizard, pilih Azure SQL Database sebagai target server, kemudian pada pilihan Migrate pilih Database. Tekan tombol Next

 image

Pertama anda harus memasukan informasi sumber data yang akan dimigrasikan ke SQL Azure, pada contoh ini saya menggunakan SQL SERVER EXPRESS, dan database yang akan dimigrasi adalah StorageDb.

image 

Kemudian tekan tombol Connect. Pilih Script all database object untuk mentransfer semua object pada database anda ke SQL Azure. Tekan tombol Next.

image 

image

Maka tools ini akan menggenerate semua script yang dibutuhkan.

image

Langkah selanjutnya adalah menambahkan database server tujuan, yaitu database server yang sudah anda buat sebelumnya di SQL Azure, masukan informasi koneksi seperti server name, username, dan password. Tekan tombol Connect.

image

image

Tekan tombol next untuk memulai proses migrasi. Setelah proses migrasi selesai akan muncul tampilan seperti gambar dibawah ini.

image

Untuk memastikan apakah semua table beserta isinya sudah berhasil dimigrasikan ke SQL Azure, maka anda dapat membuka tools SQL Server Management Studio, kemudian hubungkan dengan SQL Azure.

image

Maka anda akan dapat melihat database StorageDb yang ada di SQL Azure.

image

Demikian tutorial untuk migrasi database dari database SQL Server di server onpremis kedalam database yang ada pada SQL Azure. 

Azure Table Storage dengan ASP.NET MVC (Part 2)

Pada bagian 1 kita sudah membahas apa itu Azure Table Storage dan bagaimana cara membuat Storage Account pada layanan Azure. Selanjutnya kita akan membuat ASP.NET MVC Project yang dapat terhubung dengan layanan Storage Account yang sudah kita buat, kemudian menambahkan data pada Storage Account berupa Azure Table dan Azure Blob. Azure Table digunakan untuk menyimpan data standard yang bertipe string/number (selain blob). Azure Blob digunakan untuk menyimpan data blob seperti file image, video, pdf, dan format lain yang biasanya mempunyai ukuran relatif besar.

Membuat Project ASP.NET MVC

Buka Visual Studio 2015 kemudian buat ASP.NET MVC Project baru dengan nama  SampleTableStorage. Kemudian pada folder model tambahkan interface baru dengan nama ITableOperations.cs. Method pada interface ini akan diimplementasikan pada method selanjutnya.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Collections.Generic;
using System.Configuration;
using System;

namespace SampleTableStorage.Models
{
    public interface ITableOperations
    {
        void CreateEntity(StorageEntity entity);
        List<StorageEntity> GetEntities(string filter);
        StorageEntity GetEntity(string partitionKey,string rowKey);
    } 
}

Masih pada folder Model, tambahkan class StorageEntity.cs. Class ini digunakan untuk mendefinisikan data model yang akan dibuat pada Azure Table. Class ini berisi definisi dari field-field yang akan dibuat pada Azure Table.

using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace SampleTableStorage.Models
{
    public class StorageEntity : TableEntity
    {
        public StorageEntity()
        { }

        public StorageEntity(int storageId,string city)
        {
            this.RowKey = storageId.ToString();
            this.PartitionKey = city;
        }

        public string StorageId { get; set; }
        public string Size { get; set; }
        public string Environment { get; set; }
        public decimal PriceDay { get; set; }
        public decimal PriceMonth { get; set; }
        public string Space { get; set; }
        public string Access { get; set; }
        public string Description { get; set; }

        [Required(ErrorMessage = "Title Required !")]
        public string Title { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
        public string Picture { get; set; }
        public double Length { get; set; }
        public double Height { get; set; }
        public string Phone { get; set; }

    }
}

Setelah membuat TableEntity, maka langkah selanjutnya adalah menambahkan operasi-operasi yang akan dilakukan di Table Storage seperti membuat dan mengambil data pada Azure Table. Pada folder Model, tambahkan class dengan nama TableOperations.cs.

Untuk bekerja dengan Storage Account yang ada di Azure anda harus menambahkan string koneksi pada project anda. Anda dapat mengambil string koneksi tersebut pada portal Azure.

image

kemudian tambahkan string koneksi tersebut pada file konfirgurasi di web.config

<appSettings>
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="keepStorage" value="DefaultEndpointsProtocol=https;AccountName=keepstorage;AccountKey=<key anda>;BlobEndpoint=https://keepstorage.blob.core.windows.net/;TableEndpoint=https://keepstorage.table.core.windows.net/;QueueEndpoint=https://keepstorage.queue.core.windows.net/;FileEndpoint=https://keepstorage.file.core.windows.net/" />
</appSettings>

Setelah string koneksi ditambahkan, anda dapat menggunakan string koneksi tersebut pada aplikasi anda untuk terhubung dengan Storage Account yang ada pada layanan Azure.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Collections.Generic;
using System.Configuration;
using System;
using System.Linq;

namespace SampleTableStorage.Models
{
    public class TableOperations : ITableOperations
    {
        CloudStorageAccount storageAccount;
        CloudTableClient tableClient;

        public TableOperations()
        {
            storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["keepStorage"].ToString());
            tableClient = storageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference("keepstorage");
            table.CreateIfNotExists();
        }
        public void CreateEntity(StorageEntity entity)
        {
            CloudTable table = tableClient.GetTableReference("keepstorage");
            TableOperation insertOperation = TableOperation.Insert(entity);
            table.Execute(insertOperation);
        }

        public List<StorageEntity> GetEntities(string filter)
        {
            //List<StorageEntity> storages = new List<StorageEntity>();
            CloudTable table = tableClient.GetTableReference("keepstorage");

            List<StorageEntity> query = (from entity in table.CreateQuery<StorageEntity>()
                                               where entity.PartitionKey == "City"
                                               select entity).ToList();

            return query;
        }

        public StorageEntity GetEntity(string partitionKey, string rowKey)
        {
            StorageEntity entity = null;
            CloudTable table = tableClient.GetTableReference("keepstorage");
            entity = (from e in table.CreateQuery<StorageEntity>()
                      where e.PartitionKey == partitionKey && e.RowKey == rowKey
                      select e).FirstOrDefault();

            return entity;
        }
    }
}

Tambahkan juga class dengan nama BlobOperations.cs. Class ini akan digunakan untuk membuat dan menambahkan file blob kedalam objek Azure Blob pada Storage Account.

using System;
using System.Web;

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Configuration;
using System.Threading.Tasks;
using System.IO;


namespace SampleTableStorage.Models
{
    
    public class BlobOperations
    {
        private static CloudBlobContainer storageBlobContainer;

        public BlobOperations()
        {
            var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["keepStorage"].ToString());
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            storageBlobContainer = blobClient.GetContainerReference("blobkeepstorage");
            storageBlobContainer.CreateIfNotExists();
        }

        public CloudBlockBlob UploadBlob(HttpPostedFileBase storagePicFile)
        {
            string blobName = Guid.NewGuid().ToString() + Path.GetExtension(storagePicFile.FileName);

            CloudBlockBlob storageBlob = storageBlobContainer.GetBlockBlobReference(blobName);
            using (var fs = storagePicFile.InputStream)
            {
                storageBlob.UploadFromStream(fs);
            }

            return storageBlob;
        }
    }
}

 

Kemudian langkah selanjutnya adalah membuat controller  dengan nama StorageListController.cs. Pada controller ini kita akan menambahkan method yang digunakan untuk menambahkan data ke Azure Table dan Azure Blob.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using SampleTableStorage.Models;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;

namespace SampleTableStorage.Controllers
{
    public class StorageListController : Controller
    {
        BlobOperations blobOperations;
        TableOperations tableOperations;
               
        public StorageListController()
        {
            blobOperations = new BlobOperations();
            tableOperations = new TableOperations();
        }
        // GET: StorageList
        public ActionResult Index()
        {
            var storages = tableOperations.GetEntities("Spokane");
            return View(storages);
        }

        public ActionResult Create()
        {
            var objStorage = new StorageEntity();
            //objStorage.StorageId = Guid.NewGuid().ToString();
            objStorage.City = "Spokane";
            ViewBag.Environment = new SelectList(new List<string>() {
                "Outdoor","Indoor"
            });
            ViewBag.Access = new SelectList(new List<string>()
            {
                "Limited","Anytime"
            });

            return View();
        }

        [HttpPost]
        public ActionResult Create(StorageEntity obj,HttpPostedFileBase Picture)
        {
            //upload file to blob
            CloudBlockBlob storageBlob = null;
            if(Picture != null && Picture.ContentLength !=0)
            {
                storageBlob = blobOperations.UploadBlob(Picture);
                obj.Picture = storageBlob.Uri.ToString();
            }

            obj.City = "Spokane";
            obj.RowKey = Guid.NewGuid().ToString();
            obj.PartitionKey = obj.City;
            tableOperations.CreateEntity(obj);

            return RedirectToAction("Index","Home");
        }

    }
}

Setelah membuat controller maka untuk membuat form input yang akan kita gunakan untuk menambahkan data ke Azure Table anda dapat menambahkan view dengan nama Create.cshtml berikut.

@model SampleTableStorage.Models.StorageEntity

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm("Create","StorageList",FormMethod.Post, 
    new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    

Storage Entity


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Size, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Size, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Size, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Environment, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model=>model.Environment, (IEnumerable)ViewBag.Environment,new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Environment, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.PriceDay, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.PriceDay, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PriceDay, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.PriceMonth, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.PriceMonth, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PriceMonth, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Space, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Space, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Space, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Access, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.Access, (IEnumerable)ViewBag.Access ,new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Access, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Picture, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.ValidationMessageFor(model => model.Picture, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Length, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Length, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Length, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Height, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Height, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Height, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
</div>
</div> </div> }
@Html.ActionLink("Back to List", "Index")

Setelah itu anda dapat mencoba menjalankan aplikasi ini dan memasukan data kedalam Azure Table dan Azure Blob

image

Setelah berhasil anda dapat melihat isi dari Azure Table dan Azure Blob yang sudah anda buat di Visual Studio 2015 Cloud Explorer.

image

image

Upload File Gambar dengan ASP.NET MVC 5

Pada tutorial berikut akan dibahas cara upload file gambar kedalam folder pada aplikasi asp.net mvc. Nama file yang berhasil di upload juga akan disimpan kedalam database.

Sebelumnya buat model Author dan data context terlebih dahulu, kemudian jalankan perintah migrasi untuk menggenerate table Author di database.

   1: public class Author

   2: {

   3:     public int AuthorID { get; set; }

   4:     public string FullName { get; set; }

   5:     public string Email { get; set; }

   6:     public string PicUrl { get; set; }

   7: }

 

   1: public class SampleContext : DbContext

   2: {

   3:     public DbSet<Author> Authors { get; set; }

   4: }

Jalankan perintah untuk migrasi:

image

Pada solution explorer buat folder Images yang digunakan untuk menyimpan file.

Setelah database berhasil dibuat, tambahkan AuthorController untuk menampilkan data Author, dan menambahkan data Author baru sekaligus mengupload file.

   1: public class AuthorController : Controller

   2: {

   3:     private SampleContext db = new SampleContext();

   4:     // GET: Author

   5:     public ActionResult Index()

   6:     {

   7:         var model = db.Authors.OrderBy(a => a.FullName);

   8:  

   9:         return View(model);

  10:     }

  11:  

  12:     // GET: Author/Create

  13:     public ActionResult Create()

  14:     {

  15:         return View();

  16:     }

  17:  

  18:     // POST: Author/Create

  19:     [HttpPost]

  20:     public ActionResult Create(Author author, HttpPostedFileBase file)

  21:     {

  22:         if (ModelState.IsValid)

  23:         {

  24:             if (file != null)

  25:             {

  26:                 string pic = Path.GetFileName(file.FileName);

  27:                 string path = Path.Combine(Server.MapPath("~/Images"), pic);

  28:                 file.SaveAs(path);

  29:  

  30:                 /*using(MemoryStream ms = new MemoryStream())

  31:                 {

  32:                     file.InputStream.CopyTo(ms);

  33:                     var arr = ms.GetBuffer();

  34:                 }*/

  35:  

  36:                 var newAuthor = new Author

  37:                 {

  38:                     FullName = author.FullName,

  39:                     Email = author.Email,

  40:                     PicUrl = pic

  41:                 };

  42:                 db.Authors.Add(newAuthor);

  43:                 db.SaveChanges();

  44:             }

  45:         }

  46:  

  47:         return RedirectToAction("Index");

  48:     }

  49: }

Tambahkan view Index.cshtml untuk menampilkan data:

   1: @model IEnumerable<SampleUpload.Models.Author>

   2:  

   3: @{

   4:     ViewBag.Title = "Daftar Author";

   5: }

   6:  

   7: <h2>Daftar Author</h2>

   8:  

   9: <p>

  10:     @Html.ActionLink("Create New", "Create")

  11: </p>

  12: <table class="table">

  13:     <tr>

  14:         <th>

  15:             @Html.DisplayNameFor(model => model.FullName)

  16:         </th>

  17:         <th>

  18:             @Html.DisplayNameFor(model => model.Email)

  19:         </th>

  20:         <th>

  21:             @Html.DisplayNameFor(model => model.PicUrl)

  22:         </th>

  23:     </tr>

  24:  

  25: @foreach (var item in Model) {

  26:     <tr>

  27:         <td>

  28:             @Html.DisplayFor(modelItem => item.FullName)

  29:         </td>

  30:         <td>

  31:             @Html.DisplayFor(modelItem => item.Email)

  32:         </td>

  33:         <td>

  34:             <img src="~/Images/@item.PicUrl" alt="pic" width="100"/>

  35:         </td>

  36:     </tr>

  37: }

  38:  

  39: </table>

 

image

Tambahkan juga view Create.cshtml yang digunakan untuk menambahkan data Author baru.

   1: @model SampleUpload.Models.Author

   2:  

   3: @{

   4:     ViewBag.Title = "Create";

   5: }

   6:  

   7: <h2>Tambah Author</h2>

   8:  

   9:  

  10: @using (Html.BeginForm("Create", "Author", FormMethod.Post, new { enctype = "multipart/form-data" }))

  11: {    

  12:     <div class="form-horizontal">

  13:         <hr />

  14:         <div class="form-group">

  15:             @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-2" })

  16:             <div class="col-md-10">

  17:                 @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } })

  18:             </div>

  19:         </div>

  20:  

  21:         <div class="form-group">

  22:             @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })

  23:             <div class="col-md-10">

  24:                 @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

  25:             </div>

  26:         </div>

  27:  

  28:         <div class="form-group">

  29:             @Html.LabelFor(model => model.PicUrl, htmlAttributes: new { @class = "control-label col-md-2" })

  30:             <div class="col-md-10">

  31:                 <input type="file" name="file" id="file" />

  32:             </div>

  33:         </div>

  34:  

  35:         <div class="form-group">

  36:             <div class="col-md-offset-2 col-md-10">

  37:                 <input type="submit" value="Create" class="btn btn-default" />

  38:             </div>

  39:         </div>

  40:     </div>

  41: }

  42:  

  43: <div>

  44:     @Html.ActionLink("Back to List", "Index")

  45: </div>

  46:  

  47: @section Scripts {

  48:     @Scripts.Render("~/bundles/jqueryval")

  49: }

image

Setelah data ditambahkan, maka data baru beserta pic akan ditampilkan.

image

Selamat mencoba and Happy Coding Smile