How to save data in SQL database - Submit

2

I'm studying ASP.NET MVC, I'm using Identity to perform user control and etc.

So, I created a page, where the user will enter with 4 information:

  • Initial Mileage;
  • Final Mileage;
  • Amount of liters supplied;
  • Amount in R $.
  • So I created a Model called CombustivelModel :

    namespace OneeWeb_v2.Models
    {
        public class CombustivelModels
        {
            public string km_inicial { get; set; }
            public string km_final { get; set; }
            public string litros { get; set; }
            public string valor { get; set; }
        }
    }
    

    So I created a Controller called CombustivelController :

    namespace OneeWeb_v2.Controllers
    {
        public class CombustivelController : Controller
        {
            // GET: /Combustivel
            [Authorize]
            public ActionResult Index()
            {
                return View();
            }
        }
    }
    

    And I created your View :

    @model OneeWeb_v2.Models.CombustivelModels
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Controle de combustivel</h2>
    
    <dt>Abastecimento</dt>
    
    <div>
    
        @Html.TextBoxFor(m => m.km_inicial, new { @class = "form-control", placeholder = "KM Inicial" })
    
        @Html.TextBoxFor(m => m.km_final, new { @class = "form-control", placeholder = "KM Final" })
    
        @Html.TextBoxFor(m => m.litros, new { @class = "form-control", placeholder = "Litros" })
    
        @Html.TextBoxFor(m => m.valor, new { @class = "form-control", placeholder = "Valor R$" })
    
    </div>
    
    <div>
        <input type="submit" value="Enviar" class="btn btn-default submit" />
    </div>
    

    However, how do I save the information in the database?

    I'm using SQL Server, I've already set up ConnectionString on WebConfig

    As requested, it follows IdentityModels :

        namespace OneeWeb_v2.Models
    {
        // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
        public class ApplicationUser : IdentityUser
        {
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                // Add custom user claims here
                return userIdentity;
            }
        }
    
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext()
                : base("DefaultConnection", throwIfV1Schema: false)
            {
            }
    
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }
    }
    
        
    asked by anonymous 29.11.2016 / 17:12

    2 answers

    3

    Failed to set a primary key in your Model , and a few more things. Change to the following:

    public class Combustivel
    {
        [Key]
        public int CombustivelId { get; set; }
    
        [Required]
        public decimal km_inicial { get; set; }
        [Required]
        public decimal km_final { get; set; }
        [Required]
        public decimal litros { get; set; }
        [Required]
        [DataType(DataType.Currency)]
        public decimal valor { get; set; }
    }
    

    By Scaffolding , we can use the following cliches suggested by Microsoft for creating, editing, and deleting:

    public class CombustiveisController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
    
        // GET: Combustiveis
        public async Task<ActionResult> Indice()
        {
            return View(await db.Combustiveis.ToListAsync());
        }
    
        // GET: Combustiveis/Detalhes/5
        public async Task<ActionResult> Detalhes(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Combustivel combustivel = await db.Combustiveis.FindAsync(id);
            if (combustivel == null)
            {
                return HttpNotFound();
            }
            return View(combustivel);
        }
    
        // GET: Combustiveis/Criar
        public ActionResult Criar()
        {
            return View();
        }
    
        // POST: Combustiveis/Criar
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Criar([Bind(Include = "CombustivelId,km_inicial,km_final,litros,valor")] Combustivel combustivel)
        {
            if (ModelState.IsValid)
            {
                db.Combustiveis.Add(combustivel);
                await db.SaveChangesAsync();
                return RedirectToAction("Indice");
            }
    
            return View(combustivel);
        }
    
        // GET: Combustiveis/Editar/5
        public async Task<ActionResult> Editar(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Combustivel combustivel = await db.Combustiveis.FindAsync(id);
            if (combustivel == null)
            {
                return HttpNotFound();
            }
            return View(combustivel);
        }
    
        // POST: Combustiveis/Editar/{id}
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Editar([Bind(Include = "CombustivelId,km_inicial,km_final,litros,valor")] Combustivel combustivel)
        {
            if (ModelState.IsValid)
            {
                db.Entry(combustivel).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Indice");
            }
            return View(combustivel);
        }
    
        // GET: Combustiveis/Excluir/{id}
        public async Task<ActionResult> Excluir(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Combustivel combustivel = await db.Combustiveis.FindAsync(id);
            if (combustivel == null)
            {
                return HttpNotFound();
            }
            return View(combustivel);
        }
    
        // POST: Combustiveis/Excluir/{id}
        [HttpPost, ActionName("Excluir")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ConfirmarExclusao(int id)
        {
            Combustivel combustivel = await db.Combustivels.FindAsync(id);
            db.Combustivels.Remove(combustivel);
            await db.SaveChangesAsync();
            return RedirectToAction("Indice");
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
    

    Here I am considering that you are using Entity Framework with Microsoft SQL Server, as your question says.

    @Randrade's response maps the DbSet manually. The Scaffolding procedure automatically adds DbSet to you in context.

    DbSet ? Context? Questions about how to use? See this answer .

    Views are also clichés:

    Create.cshtml

    @model OneeWeb_v2.Models.Combustivel
    
    @{
        ViewBag.Title = "Create";
    }
    
    <h2>Create</h2>
    
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>Combustivel</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.km_inicial, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.km_inicial, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.km_inicial, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.km_final, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.km_final, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.km_final, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.litros, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.litros, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.litros, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.valor, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.valor, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.valor, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Criar" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Voltar para Listagem", "Indice")
    </div>
    

    Edit.cshtml

    @model OneeWeb_v2.Models.Combustivel
    
    @{
        ViewBag.Title = "Edit";
    }
    
    <h2>Edit</h2>
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>Combustivel</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.CombustivelId)
    
            <div class="form-group">
                @Html.LabelFor(model => model.km_inicial, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.km_inicial, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.km_inicial, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.km_final, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.km_final, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.km_final, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.litros, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.litros, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.litros, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.valor, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.valor, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.valor, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Salvar" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Voltar para Listagem", "Indice")
    </div>
    

    Delete.cshtml

    @model OneeWeb_v2.Models.Combustivel
    
    @{
        ViewBag.Title = "Delete";
    }
    
    <h2>Delete</h2>
    
    <h3>Você tem certeza de que deseja excluir este registro?</h3>
    <div>
        <h4>Combustivel</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.km_inicial)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.km_inicial)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.km_final)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.km_final)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.litros)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.litros)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.valor)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.valor)
            </dd>
    
        </dl>
    
        @using (Html.BeginForm()) {
            @Html.AntiForgeryToken()
    
            <div class="form-actions no-color">
                <input type="submit" value="Excluir" class="btn btn-default" /> |
                @Html.ActionLink("Voltar para Listagem", "Indice")
            </div>
        }
    </div>
    

    Details.cshtml

    @model OneeWeb_v2.Models.Combustivel
    
    @{
        ViewBag.Title = "Details";
    }
    
    <h2>Details</h2>
    
    <div>
        <h4>Combustivel</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.km_inicial)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.km_inicial)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.km_final)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.km_final)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.litros)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.litros)
            </dd>
    
            <dt>
                @Html.DisplayNameFor(model => model.valor)
            </dt>
    
            <dd>
                @Html.DisplayFor(model => model.valor)
            </dd>
    
        </dl>
    </div>
    <p>
        @Html.ActionLink("Editar", "Editar", new { id = Model.CombustivelId }) |
        @Html.ActionLink("Voltar para Listagem", "Indice")
    </p>
    
        
    29.11.2016 / 17:57
    3

    First step, update your IdentityModels to map your model, like this:

    namespace OneeWeb_v2.Models
    {
        // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
        public class ApplicationUser : IdentityUser
        {
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                // Add custom user claims here
                return userIdentity;
            }
        }
    
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext()
                : base("DefaultConnection", throwIfV1Schema: false)
            {
            }
    
            //Aqui que está a alteração
            public DbSet<CombustivelModels> Combustiveis { get; set; }
    
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }
    }
    

    After this, let's "normalize" your controller. To do this, we'll create a POST method to save the typed data, like this:

    namespace OneeWeb_v2.Controllers
    {
        public class CombustivelController : Controller
        {
            private ApplicationDbContext db = new ApplicationDbContext();
    
            // GET: /Combustivel
            [Authorize]
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult Index(CombustivelModels model)
            {
                if (ModelState.IsValid)
                {
                    db.Combustiveis.Add(model);
                    db.SaveChanges();
    
                    return RedirectToAction("Index");
                }
                return View(model);
            }
        }
    }
    

    And, we add the Html.BeginForm() in View to "she knows" what to do with the data, like this:

    @using (Html.BeginForm())
    {
        <div>
    
            @Html.TextBoxFor(m => m.km_inicial, new { @class = "form-control", placeholder = "KM Inicial" })
    
            @Html.TextBoxFor(m => m.km_final, new { @class = "form-control", placeholder = "KM Final" })
    
            @Html.TextBoxFor(m => m.litros, new { @class = "form-control", placeholder = "Litros" })
    
            @Html.TextBoxFor(m => m.valor, new { @class = "form-control", placeholder = "Valor R$" })
    
        </div>
    
        <div>
            <input type="submit" value="Enviar" class="btn btn-default submit" />
        </div>
    }
    

    Now, this can all be automatically generated by scaffolding . This answer shows in detail how to do this .

      

    The suggestion is that your Actions have the name of what you will do, for example, Create to create something, etc. I added Action POST with the name of Index just to make it easier to understand.

        
    29.11.2016 / 17:59