Asp.net Core Web Application File Upload Bootstrap Modal Popup

Upload file using Ajax form and Modal dialog in ASP.Net MVC

In my previous commodity, I have explained to y'all how to use a modal dialog to add, edit, delete and detect records in asp.net MVC by using a razor view engine.

In this commodity, I am going to explain and demonstrate how to upload images by using ajax form and modal dialog in ASP.Net MVC.

To build this sample application y'all must take basic knowledge of jQuery. I am using entity framework code first model to add and update the information in the database.

1). Open Visual Studio 2010

2). Create a new ASP.Cyberspace MVC 4 web application and named information technology as AjaxFormMVC for this application.

3). Choose Razor as the View and click OK

4). Add together a Controller in your project and give name equally HomeController.

five). Create a model class in the Model folder as shown below:

Add a connexion string in the web.config file under the configuration tag:

  <connectionStrings>          
    <add name='ActorDbContext'connectionString='Data Source=.\SQLEXPRESS;Initial Catalog=ActorDb;Integrated Security=true;'providerName='System.Data.SqlClient' />
  </connectionStrings>

 Add a Partial View _ActorList.cshtml in Views/Home binder and add the following code in this partial view:

@model IEnumerable<AjaxFormMVC.Models.Actor>          
<p>
    @Html.ActionLink('Create New', 'Create', aught, new { @class = 'createActor', title = 'Create Actor' })
</p>
<tabular array style='edge: 1px solid blackness;' cellpadding='10'>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Proper name)
        </thursday>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <thursday>
            @Html.DisplayNameFor(model => model.Image)
        </th>
        <th>
        </thursday>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td valign='superlative'>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td valign='top'>
                @Html.DisplayFor(modelItem => item.Clarification)
            </td>
            <td valign='superlative'>
                <img src='@Url.Content('~/Content/Actors/' + item.ActorID + '/' + item.Image + '')' alt='@item.Proper name' width='100px' height='100px' />
            </td>
            <td valign='acme'>
                @Html.ActionLink('Edit', 'Edit', new { id = item.ActorID }, new { @class = 'createActor', title = 'Edit Actor' })
                |
                @Html.ActionLink('Delete', 'Delete', new { id = item.ActorID })
            </td>
        </tr>
    }
</table>

Add a view Alphabetize  and replace with the code given below.

Must include these three files ( jquery-1.seven.1.min.js, jquery-ui-1.8.20.min.js, form_ajax.js) under Scripts folder and include themes in the Content folder.Themes binder comprise all the necessary CSS files.

                      @model IEnumerable<AjaxFormMVC.Models.Thespian>              
@{
    Layout = zero;
}
<!DOCTYPE html>
<html>
<head>
    <meta name='viewport' content='width=device-width' />
    <title>Index</championship>
    <link href='@Url.Content('~/Content/themes/base/minified/jquery-ui.min.css')' rel='stylesheet' type='text/css' />
    <script src='@Url.Content('~/Scripts/jquery-one.7.1.min.js')' type='text/javascript'></script>
    <script src='@Url.Content('~/Scripts/jquery-ui-one.eight.xx.min.js')' type='text/javascript'></script>
    <script src='@Url.Content('~/Scripts/form_ajax.js')' type='text/javascript'></script>
    <script blazon='text/javascript'>
        $(document).ready(role () {

            $.ajaxSetup({ enshroud: false });

            $('.createActor').live('click', function (e) {
                var $url = $(this).attr('href');
                var $championship = $(this).attr('title');

                var $dialog = $('<div id='modalDialog'></div>');
                $dialog.empty();
                $dialog.load($url).dialog({
                    autoOpen: faux,
                    title: $title,
                    resizable: faux,
                    height: 300,
                    width: 380,
                    testify: { outcome: 'drop', direction: 'up' },
                    modal: true,
                    draggable: true
                });
                $dialog.dialog('open up');
                return false;
            });

            $('#btncancel').live('click', function (east) {
                $('#modalDialog').dialog('close');
            });
        });
    </script>
</head>
<body>
    <div id='actorList'>
        @Html.Fractional('_ActorList', Model)
    </div>
</body>
</html>

 Add together an _Actor.cshtml partial view in the aforementioned binder Views\Home and add the post-obit code:

@model AjaxFormMVC.Models.Thespian          
<script type='text/javascript'>
    $(document).ready(function () {
        $('#frmCreateActor').ajaxForm(function () {
            $('#modalDialog').dialog('shut');
            $.post('@Url.Action('GetActorList', 'Home')', function (data) {
                $('#actorList').html(data);
            });
        })
    });
</script>
@using (Html.BeginForm('Create', 'Home', FormMethod.Postal service, new { @id = 'frmCreateActor', @enctype = 'multipart/class-information' }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <fable>Thespian</fable>
        <div class='editor-characterization'>
            @Html.LabelFor(model => model.Name)
        </div>
        <div class='editor-field'>
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Proper noun)
        </div>
        <div class='editor-characterization'>
            @Html.LabelFor(model => model.Clarification)
        </div>
        <div class='editor-field'>
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
        <div grade='editor-characterization'>
            @Html.LabelFor(model => model.Paradigm)
        </div>
        <div class='editor-field'>
            <input type='file' name='imageFile' id='imageFile' />
            @Html.ValidationMessageFor(model => model.Image)
        </div>
        <p>
            @if (ViewBag.IsUpdate !=null && ViewBag.IsUpdate)
            {
                @Html.HiddenFor(model => model.ActorID);
                <input proper noun='cmd' type='submit' value='Update' />
            }
            else
            {
                <input proper name='cmd' type='submit' value='Create' />
            }
            <input type='push button' value='Abolish' id='btncancel' />
        </p>
    </fieldset>
}

Create object of ActorDbContext in HomeController:

ActorDbContext db = new ActorDbContext();

 Add the following actions in HomeController:

                 public ActionResult Alphabetize()            
        {
            return View(db.Actors.ToList());
        }
        public ActionResult Create()
        {
            return PartialView('_Actor');
        }
        [HttpPost]
        public ActionResult Create(HttpPostedFileBase imageFile, Player model, string cmd)
        {
            effort
            {
                if (imageFile != null && imageFile.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(imageFile.FileName);
                    if (cmd == 'Create')
                    {
                        model.Prototype = fileName;
                        db.Actors.Add(model);
                        db.SaveChanges();
                    }
                    else
                    {
                        var actor = db.Actors.Where(m => m.ActorID == model.ActorID).FirstOrDefault();
                        if (thespian != nil)
                        {
                            actor.Image = fileName;
                            db.SaveChanges();
                        }
                    }

                    var path = Path.Combine(Server.MapPath('~/Content/Actors/'), model.ActorID.ToString());
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    imageFile.SaveAs(path + '/' + fileName);
                }
            }
            catch { }

            return RedirectToAction('Index');
        }

        public ActionResult Edit(int id)
        {
            var actor = db.Actors.Where(m => m.ActorID == id).FirstOrDefault();
            ViewBag.IsUpdate = true;
            return PartialView('_Actor', role player);
        }

        public ActionResult Delete(int id)
        {
            var actor = db.Actors.FirstOrDefault(m => k.ActorID == id);
            if (actor != null)
            {
                db.Actors.Remove(role player);
                db.SaveChanges();
            }
            return RedirectToAction('Index');
        }
        public ActionResult GetActorList()
        {
            return PartialView('_ActorList', db.Actors.ToList());
        }

 Now, run or debug your application. The awarding will something look like beneath:

Upload file using Ajax form and Modal dialog in ASP.Net MVC

To create a new histrion record, click on Create New and enter the information for the actor and scan the image.

When you click on Create push it volition add together the tape both in the database and folder (Content\Actors\{ActorID}\).

Upload file using Ajax form and Modal dialog in ASP.Net MVC

The result will something look like the below screenshot after adding the in a higher place tape.

Upload file using Ajax form and Modal dialog in ASP.Net MVC

Same fashion, you can edit and delete the records of the actor by using Edit and Delete option given in each row.

Cheers for reading this article. You can enter your valuable comments and suggestion to improve this commodity in the comment box.

Concluding updated:1/iii/2020 10:53:44 PM

baumannanythe1962.blogspot.com

Source: https://www.mindstick.com/articles/1120/upload-file-using-ajax-form-and-modal-dialog-in-asp-dot-net-mvc

0 Response to "Asp.net Core Web Application File Upload Bootstrap Modal Popup"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel