How to save data to SQL database - Submit

Asked

Viewed 490 times

2

I am studying ASP.NET MVC, I am using the Identity to carry out user control and etc.

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

  1. Mileage Initial;
  2. Mileage Final;
  3. Quantity of litres supplied;
  4. Value 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 am using SQL Server, I have configured the ConnectionString in the WebConfig

As requested, follow the 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();
        }
    }
}
  • Are you using the Entity framework? If so, you have already set up the Dbcontext?

  • Yes I am using, and the Dbcontext configuration is in IdentityModels? if yes already!

  • Pole also the IdentityModels

  • as requested, edition made.

  • @Thomaserichpimentel You never used Entityframework?

  • No, I’m adventuring now. rs

Show 1 more comment

2 answers

3


Missing 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; }
}

For Scaffolding, we may use the following clichés suggested by Microsoft for creation, editing and deletion:

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.

The reply from @Randrade maps the DbSet manually. The procedure of Scaffolding adds the DbSet automatically for you to the context.

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

As 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>

3

First step, update your IdentityModels to map your model in this way:

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 that, we will "normalize" your controller. To do this, we will create a method POST to save the typed data in this way:

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 for "she knows" what to do with the data, this way:

@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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.