How can i save changes made to the database - asp.net-mvc

I have the following action for Edit,
In the view i have the following code
<form asp-action="Edit" class="form-horizontal">
<input type="text" asp-for="Code" value="#Model.Code" class="form-control" />
<button class="btn btn-success Product-edit-button" role="button">Save</button>
</form>
How can i save changes to Database on button click?
Here is what i tried, edit model look like
public async Task<IActionResult> editModel(int? id)
{
if (id == null)
{
return NotFound();
}
var ProductList = (await ProductService.GetProducts()).ToList();
var Product = ProductList.FirstOrDefault(a => a.ID == id);
if (Product == null)
{
return NotFound();
}
return View(Product);
}
Edit Action looks like as follow
public async Task<IActionResult> Edit(ProductEditModel editModel)
{
if (id == null)
{
return NotFound();
}
var ProductList = (await ProductService.GetProducts()).ToList();
var Product = ProductList.FirstOrDefault(a => a.ID == id);
if (Product == null)
{
return NotFound();
}
Product.Code = editModel.Code;
ProductService.EditProduct(Product);
return View(Product);
}

You need another action that accept POST request and send edited data to it.
public async Task<IActionResult> Edit(ProductEditModel editModel)
{
if (id == null)
{
return NotFound();
}
var ProductList = (await ProductService.GetProducts()).ToList();
var Product = ProductList.FirstOrDefault(a => a.ID ==editModel.Id);
if (Product == null)
{
return NotFound();
}
Product.Code=editModel.Code;
ProductService.EditProduct(Product);
return View(Product);
}
The Model :
public class ProductEditModel {
public int Id {get;set;}
public string code{get; set;}
}
The View:
<form asp-action="Edit" class="form-horizontal">
<input type="hidden" asp-for="Id" value="#Model.Id" class="form-control" />
<input type="text" asp-for="Code" value="#Model.Code" class="form-control" />
<button class="btn btn-success Product-edit-button" role="button">Save</button>
</form>

Here is a working demo like below:
1.Model:
public class ProductEditModel
{
public int ID { get; set; }
public string Code { get; set; }
}
2.View(Edit.cshtml):
#model ProductEditModel
<h4>ProductEditModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ID" />
<div class="form-group">
<label asp-for="Code" class="control-label"></label>
<input asp-for="Code" class="form-control" />
<span asp-validation-for="Code" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
3.Controller:
public class ProductEditModelsController : Controller
{
private readonly YourContext _context;
public ProductEditModelsController(YourContext context)
{
_context = context;
}
// GET: ProductEditModels/Edit/5
//display edit view
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var productEditModel = await _context.ProductEditModel.FindAsync(id);
if (productEditModel == null)
{
return NotFound();
}
return View(productEditModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ProductEditModel productEditModel)
{
if (ModelState.IsValid)
{
_context.Update(productEditModel);//update model
await _context.SaveChangesAsync();//save to database
return RedirectToAction(nameof(Index));
}
return View(productEditModel);
}
}
4.DbContext:
public class YourContext: DbContext
{
public YourContext(DbContextOptions<YourContext> options)
: base(options)
{
}
public DbSet<ProductEditModel> ProductEditModel { get; set; }
}
5.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<YourContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnnection"))); //connect to sql server
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Privacy}/{id?}");
});
}
Result:
Update:
1.Index.cshtml:
#model IEnumerable<ProductEditModel>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Code)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Code)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="#item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="#item.ID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
2.Index action in controller:
public async Task<IActionResult> Index()
{
return View(await _context.ProductEditModel.ToListAsync());
}
If you do not understand successfully,please learn the mvc tutorial below first.
Reference:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-3.1&tabs=visual-studio

Related

One-To-Many relationship between ApplicationUser and an other object

I am struggling trying to implement à create action and an index for my controller.
Basically, I want each user to have multiple pizzas.
I want the connected user to create his own pizzas.
And in the index of my controller I want to show, only the pizzas created by the current connected user.
Here are my models :
1/Pizzas :
public class PizzaModel
{
[Key]
public int PizzaID { get; set; }
[Display(Name = "Nom")]
public string nom { get; set; }
[Display(Name = "Prix(€)")]
public float prix { get; set; }
[Display(Name = "Végétarienne")]
public bool vegetarienne { get; set; }
[Display(Name = "Ingrédients")]
public string ingredients { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public string ApplicationUserId { get; set; }
}
2/ ApplicationUser :
public class ApplicationUser : IdentityUser
{
public ICollection<PizzaModel> Pizzas { get; set; }
}
3/ This is my Context :
public class AuthDbContext : IdentityDbContext<ApplicationUser>
{
public AuthDbContext(DbContextOptions<AuthDbContext> options) : base(options)
{
}
public DbSet<PizzaModel> Pizzas { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ApplicationUser>()
.HasMany(p => p.Pizzas)
.WithOne(u => u.ApplicationUser)
.IsRequired()
.HasForeignKey(p => p.ApplicationUserId);
base.OnModelCreating(builder);
}
I want to create a "create action" and an "index action" that shows only the pizzas created by the current connected user. Here is what I have done so far :
1/ Index action method :
public async Task<IActionResult> Index(string searchByName)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
IEnumerable<PizzaModel> pizzas = new List<PizzaModel>();
pizzas = _context.Pizzas.Where(x => x.ApplicationUserId == userId);
return View(pizzas);
}
2/ Create Action Method :
public async Task<IActionResult> Create(PizzaModel model)
{
_context.ApplicationUsers.Add(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index), "Pizza");
}
Could you please help me with these 2 actions (Create and Index) ?
According to your Model and DbContext, I create the actions as below: I'm using the Home Controller and Project name is "WebApplication3"
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext _dbContext;
public HomeController(ILogger<HomeController> logger, ApplicationDbContext dbContext)
{
_logger = logger;
_dbContext = dbContext;
}
public IActionResult Index()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
IEnumerable<PizzaModel> pizzas = new List<PizzaModel>();
pizzas = _dbContext.Pizzas.Where(x => x.ApplicationUserId == userId);
return View(pizzas);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(PizzaModel model)
{
//Note: if you check the ModelState.IsValid, it will return false, because there is no ApplicationID and PizzaID,
//you can create a view model to enter the new value, then, convert it to PizzaModel
//validate the model
//if (ModelState.IsValid)
//{
//get current user id
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId != null)
{
//based on the userid to find current user and get its pizzas.
var currentuser = _dbContext.ApplicationUsers.Include(c => c.Pizzas).First(c => c.Id == userId);
List<PizzaModel> pizzas = new List<PizzaModel>();
pizzas = currentuser.Pizzas.ToList();
//add the new item to pizza list
pizzas.Add(new PizzaModel()
{
nom = model.nom,
prix = model.prix,
vegetarienne = model.vegetarienne,
ingredients = model.ingredients
});
//update the pizzas for current user.
currentuser.Pizzas = pizzas;
await _dbContext.SaveChangesAsync();
}
return RedirectToAction(nameof(Index));
//}
//else
//{
// return View();
//}
}
The Index view as below:
#model IEnumerable<WebApplication3.Data.PizzaModel>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.PizzaID)
</th>
<th>
#Html.DisplayNameFor(model => model.nom)
</th>
<th>
#Html.DisplayNameFor(model => model.prix)
</th>
<th>
#Html.DisplayNameFor(model => model.vegetarienne)
</th>
<th>
#Html.DisplayNameFor(model => model.ingredients)
</th>
<th>
#Html.DisplayNameFor(model => model.ApplicationUserId)
</th>
<th></th>
</tr>
</thead>
<tbody>
#if(Model.ToList().Count > 0)
{
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.PizzaID)
</td>
<td>
#Html.DisplayFor(modelItem => item.nom)
</td>
<td>
#Html.DisplayFor(modelItem => item.prix)
</td>
<td>
#Html.DisplayFor(modelItem => item.vegetarienne)
</td>
<td>
#Html.DisplayFor(modelItem => item.ingredients)
</td>
<td>
#Html.DisplayFor(modelItem => item.ApplicationUserId)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
}
else
{
<tr><td colspan="7">Empty</td></tr>
}
</tbody>
</table>
<p>
<a asp-action="Create">Create New Pizza</a>
</p>
The Create View:
#model WebApplication3.Data.PizzaModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>PizzaModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="nom" class="control-label"></label>
<input asp-for="nom" class="form-control" />
<span asp-validation-for="nom" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="prix" class="control-label"></label>
<input asp-for="prix" class="form-control" />
<span asp-validation-for="prix" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="vegetarienne" /> #Html.DisplayNameFor(model => model.vegetarienne)
</label>
</div>
<div class="form-group">
<label asp-for="ingredients" class="control-label"></label>
<input asp-for="ingredients" class="form-control" />
<span asp-validation-for="ingredients" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
The result as below:
Generally, in the HttpPost method such as the Create or Update action method, we need to validte the model is valid or not, then based on the result to show validation message or go the next steps. You can refer the following tutorials:
Model validation in ASP.NET Core MVC and Razor Pages
Tutorial: Implement CRUD Functionality - ASP.NET MVC with EF Core

Pay pal integration using 3-rd party shopping cart MVC .NET core

I'm trying to integrate pay pal into my custom cart. I have used information on official Pay Pal site for integration. I'm using my sandbox account for testing the payment. It dose not seem to work and I don't know what is causing the problem. When calling the pay Pal view it just returns pay pal error.
Here is the PayPalPartialView:
#{
int count = 1;
}
<form class="paypalform" action="https://www.paypal.com/us/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="sb-2mrjh7443549#personal.example.com">
#foreach (var item in Model)
{
<input type="hidden" name="item_name_#count" value="#item.ProductName" />
<input type="hidden" name="amount_#count" value="#item.Price" />
<input type="hidden" name="quantity_#count" value="#item.Quantity" />
count++;
}
<input type="hidden" name="currency_code" value="EUR">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
Also the cart index view:
#model CartViewModel
#{
ViewData["Title"] = "Cart Overview";
}
#if (Model.CartItems.Count > 0)
{
<h1>Cart Overview</h1>
<div class="cartWrapper">
<div class="cartbg d-none">
<h3 class="text-center">Redirecting you to paypal...</h3>
<img src="~/Images/ajax_loader.gif" />
</div>
<table class="table">
<tr>
<th>Product</th>
<th>Quantity</th>
<th></th>
<th>Price</th>
<th>Total</th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr>
<td>#item.ProductName</td>
<td>#item.Quantity</td>
<td>
<a asp-action="Add" asp-route-id="#item.ProductId" class="btn btn-sm btn-primary">+</a>
<a asp-action="Decrease" asp-route-id="#item.ProductId" class="btn btn-sm btn-success">-</a>
<a asp-action="Remove" asp-route-id="#item.ProductId" class="btn btn-sm btn-danger">Remove</a>
</td>
<td>#item.Price.ToString("C2")</td>
<td>#Model.CartItems.Where(x => x.ProductId == item.ProductId).Sum(x => x.Quantity * x.Price).ToString("C2")</td>
</tr>
}
<tr>
<td class="text-right" colspan="4">Grand total: #Model.GrandTotal.ToString("C2")</td>
</tr>
<tr>
<td class="text-right" colspan="4">
<a asp-action="Clear" class="btn btn-danger">Clear cart</a>
Checkout
</td>
</tr>
</table>
</div>
}
else
{
<h3 class="display-4 text-center">Cart is empty</h3>
}
<partial name="~/Views/Cart/_PayPalPartial.cshtml" for="CartItems" />
#section Scripts{
<script>
$(function () {
$("a.checkout").click(function (e) {
e.preventDefault();
$("div.cartbg").removeClass("d-none");
$.get("/cart/clear", {}, function () {
$("form.paypalform").submit();
});
});
});
</script>
}
the cart controller:
using CmsShoppingCart.Infrastructure;
using CmsShoppingCart.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CmsShoppingCart.Controllers
{
public class CartController : Controller
{
private readonly CmsSchoppingCartContext context;
public CartController(CmsSchoppingCartContext context)
{
this.context = context;
}
//GET /cart
public IActionResult Index()
{
List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart") ?? new List<CartItem>();
CartViewModel cartVM = new CartViewModel
{
CartItems = cart,
GrandTotal = cart.Sum(x => x.Price * x.Quantity)
};
return View(cartVM);
}
//GET /cart/add/id
public async Task<IActionResult> Add(int id)
{
Product product = await context.Products.FindAsync(id);
List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart") ?? new List<CartItem>();
CartItem cartItem = cart.Where(x => x.ProductId == id).FirstOrDefault();
if (cartItem == null)
{
cart.Add(new CartItem(product));
}
else
{
cartItem.Quantity += 1;
product.Quantity--;
context.SaveChanges();
}
HttpContext.Session.SetJson("Cart", cart);
if(HttpContext.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
return RedirectToAction("Index");
return ViewComponent("SmallCart");
}
//GET /cart/decrease/id
public async Task<IActionResult> Decrease(int id)
{
Product product = await context.Products.FindAsync(id);
List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart");
CartItem cartItem = cart.Where(x => x.ProductId == id).FirstOrDefault();
if (cartItem.Quantity > 1)
{
--cartItem.Quantity;
product.Quantity++;
context.SaveChanges();
}
else
{
cart.RemoveAll(x => x.ProductId == id);
}
if (cart.Count == 0)
{
HttpContext.Session.Remove("Cart");
}
else
{
HttpContext.Session.SetJson("Cart", cart);
}
return RedirectToAction("Index");
}
//GET /cart/remove/id
public IActionResult Remove(int id)
{
List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart");
cart.RemoveAll(x => x.ProductId == id);
if (cart.Count == 0)
{
HttpContext.Session.Remove("Cart");
}
else
{
HttpContext.Session.SetJson("Cart", cart);
}
return RedirectToAction("Index");
}
//GET /cart/clear
public IActionResult Clear()
{
HttpContext.Session.Remove("Cart");
// return RedirectToAction("Page", "Pages");
//return Redirect("/");
if (HttpContext.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
return Redirect(Request.Headers["Referer"].ToString());
return Ok();
}
}
}
Cart model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CmsShoppingCart.Models
{
public class CartItem
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
public decimal Total { get { return Quantity * Price; } }
public string Image { get; set; }
public CartItem()
{
}
public CartItem(Product product)
{
ProductId = product.Id;
ProductName = product.Name;
Price = product.Price;
Quantity = 1;
Image = product.Image;
}
}
}
And cart View model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CmsShoppingCart.Models
{
public class CartViewModel
{
public List<CartItem> CartItems { get; set; }
public decimal GrandTotal { get; set; }
}
}
Its too late but for someone who are wondering about this issue:
Change PayPal Sandbox Url to:
https://www.sandbox.paypal.com/cgi-bin/webscr

With Asp.net Mvc I would like to select multiple languages in which members can speak using Dropdownlist in a form

I didn't understand how to send and save the selected languages.
When I use Plugin (select2), there is a problem with Js and other Plugin in the template.
View:
<div class="form-group">
<label class="col-md-4 control-label">Which Languages Speak *</label>
<span style="color:red;"><small> >>> You can select multiple languages.</small></span>
<div class="col-md-8 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon" style="max-width: 100%;"><i class="glyphicon glyphicon-list"></i></span>
<select class="form-control" name="Dil_Id[]" multiple="multiple" id="select" required>
#foreach (var item in dilList)
{
<option value="#item.Id">#item.DilAdi_Eng</option>
}
</select>
</div>
</div>
</div>
Controller:
public class YeniIhtiyacSahibiController : Controller
{
// GET: IhtiyacSahibi/YeniIhtiyacSahibi
IhtiyacSahibiUyeBLL _ISUye = new IhtiyacSahibiUyeBLL();
ISUDilBLL _isuDil = new ISUDilBLL(); // members languages
public ActionResult Index(int Id = 0)
{
var model = _ISUye.GetById(Id);
ViewBag.Mesaj = GenelAraclarBLL.KayitYeni(); // Message Succesfull
return View(model);
}
[HttpPost]
public ActionResult Index(IhtiyacSahibiUye model)
{
return View(model);
}
}
What can i do without plugin and how can i send and save that items? I don't know how to make and send the list. Thank you for your time.
I post forms with select2 like this:
$.ajax({
url: "/Projects/Edit/",
type: "POST",
data: {
__RequestVerificationToken: token,
ProjectManagersString: $("#ProjectManagers").val(), //select 2 control value
}
})
Controller:
public async Task<ActionResult> Edit(Project project)
{
if (Request.Form["ProjectManagersString[]"] != null)
{
foreach (var pmstring in Request.Form["ProjectManagersString[]"].Split(','))
{
}
}
}
The binding of the form controls is done in the parameter indicated in the Post method of the controller. Following an example to access the selected value.
The Model
public class Mymodel
{
    public List<SelectListItem> dilList { get; set; }
    public int? Id { get; set; }
}
The Controller
public class YeniIhtiyacSahibiController : Controller
{
[HttpGet]
public ActionResult Index()
{
//Get Method
return View(model);
}
[HttpPost]
public ActionResult Index(IhtiyacSahibiUye model)
{
car selectedId=model.Id
return View(model);
}
}
The View
#model namespace.Models.Mymodel 
#{
    Layout = null;
} 
<html>
<head>
</head>
<body>
 #using (Html.BeginForm("Index", "YeniIhtiyacSahibiController", FormMethod.Post))
    {
        <table>
            <tr>
                <td>
                    DilAdi_Eng:
                </td>
                <td>
                    #Html.DropDownListFor(m => m.Id, Model.dilList, "Language")
                </td>
            </tr>           
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="Submit"/>
                </td>
            </tr>
        </table>
    }
</body>
</html>
Cordialement

Send E-mail via ActionLink in Bootstrap Modal

I'm working on a small "Rent-a-car" application. I have a list of Cars that client can see and i want to implement "Order feature" on that list. Every car should have order button on his side. When the client chooses car and presses button "Order" i want to have opened Bootstrap Modal that says something like "You want to order car that client selected , please enter your personal information". Then he will enter his name, email, and phone number. When he enters that he will press "Submit" button on that modal and he will get message something like "We sent a payment link and instruction for paying on your email. Please check your email." Then the client will get email that will say "You want to order car that the client selected . Please read following instructions: Some text"
I suppose i can do this with Action Links but i don't know how to implement it in my existing code
Please note: This doesn't have to be made using Bootstrap Modals. I am opened for your suggestions. Please review my existing code.
This is my Car model:
public class Car
{
[Key]
public int CarID { get; set; }
public string Model { get; set; }
[DisplayName("Year of production")]
public int YearOfProduction { get; set; }
public string Price { get; set; }
public virtual ICollection<FilePath> FilePaths { get; set; }
[DisplayName("Air Conditioning")]
public string AirConditioning { get; set; }
[DisplayName("Engine")]
public string EngineType { get; set; }
public string Transmission { get; set; }
public string Suitcases { get; set; }
public string Seats { get; set; }
}
This is my Cars controller:
public class CarsController : Controller
{
private CarContext db = new CarContext();
// GET: Cars
public ActionResult Index()
{
return View(db.Cars.ToList());
}
// GET: Cars/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//Car car = db.Cars.Find(id);
Car car = db.Cars.Include(i => i.FilePaths).SingleOrDefault(i => i.CarID == id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// GET: Cars/Create
[Authorize(Roles = "Administrator")]
public ActionResult Create()
{
return View();
}
// POST: Cars/Create
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Model,YearOfProduction,Price,AirConditioning,EngineType,Transmission, Suitcases, Seats")] Car car, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var photo = new FilePath
{
FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(upload.FileName), //uniqueness of the file name
FileType = FileType.Photo
};
car.FilePaths = new List<FilePath>();
upload.SaveAs(Path.Combine(Server.MapPath("~/Images/Cars"), photo.FileName));
car.FilePaths.Add(photo);
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Edit/5
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CarID,Model,YearOfProduction,Price,AirConditioning,EngineType,Transmission, Suitcases, Seats")] Car car, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var photo = new FilePath
{
FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(upload.FileName), //uniqueness of the file name
FileType = FileType.Photo
};
car.FilePaths = new List<FilePath>();
upload.SaveAs(Path.Combine(Server.MapPath("~/Images/Cars"), photo.FileName));
car.FilePaths.Add(photo);
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Delete/5
[Authorize(Roles = "Administrator")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// POST: Cars/Delete/5
[Authorize(Roles = "Administrator")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Car car = db.Cars.Find(id);
db.Cars.Remove(car);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
This is my Index view of the Cars controller where i put list of the cars and modals for ordering:
#model IEnumerable<Testing_identity_2.Models.Car>
#{
ViewBag.Title = "Index";
}
<h2>AVAILABLE CARS</h2>
#if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
<p>
#Html.ActionLink("Create New", "Create")
</p>
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Model)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td class="col-md-3">
#Html.DisplayFor(modelItem => item.Model)
</td>
<td class="col-md-2">
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<button class="btn btn-default btn-sm" data-target="#orderModal" data-toggle="modal">Order</button>
#Html.ActionLink("Details", "Details", new {id = item.CarID}, new {#class = "btn btn-default btn-sm"})
#if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
#Html.ActionLink("Edit", "Edit", new {id = item.CarID}, new {#class = "btn btn-default btn-sm"})
}
#if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
#Html.ActionLink("Delete", "Delete", new {id = item.CarID}, new {#class = "btn btn-default btn-sm"})
}
</td>
</tr>
}
</table>
<div class="modal" data-keyboard="false" data-backdrop="static" id="orderModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Please enter your personal information</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input class="form-control" placeholder="Name" type="text" id="inputName" />
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input class="form-control" placeholder="Email" type="text" id="inputEmail" />
</div>
<div class="form-group">
<label for="inputPhoneNumber">Phone Number</label>
<input class="form-control" placeholder="Phone Number" type="text" id="inputPhoneNumber" />
</div>
</form>
</div>
<div class="modal-footer">
<button id="btnSubmitModal" class="btn btn-primary">Submit</button>
<button class="btn btn-primary" id="btnHideModal2">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" data-keyboard="false" data-backdrop="static" id="orderModal1" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<form>
<h4 class="modal-title">We sent a payment link on your email.</h4>
<br />
<h4 class="modal-title">Please check your email.</h4>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="btnHideModal1">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmitModal').click(function () {
$('#orderModal').modal('hide');
});
$('#orderModal').on('hide.bs.modal', function (){
$('#orderModal1').modal('show');
});
$('#btnHideModal1').click(function () {
$('#orderModal1').modal('hide');
});
$('#btnHideModal2').click(function () {
$('#orderModal').modal('hide');
$('#orderModal1').modal('hide');
});
});
</script>
There are several things that you are asking for. First, You need to add an actionlink tag with a binding id in your #foreach loop, for example:
#Html.Actionlink("Order car here!", "Order", new { id=item.CarID })
With the controller actionresult looking similar to this:
Public ActionResult Order(int id)
{
return View("Order");
}
Second, you want to have an order page in which the user can enter their data, using razor or angularJS. I recommend that you have a separate model for storing user data:
class client
{
public int userID { get; set; }
public string email { get; set; }
public string Name { get; set; }
public int PhoneNumber { get; set; }
}
An example Order page:
<div>
<div>
#Html.Label("emailaddress","Email address")
#Html.Editor("Email")
</div>
<div>
#Html.Label("NameLabel", "First Name")
#Html.Editor("Name")
</div>
<div>
#Html.Label("PhoneNumberLabel", "Phone Number")
#Html.Editor("PhoneNumber")
</div>
#Html.ActionLink("Submit order form", "submitOrder", new { email=Model.email, name=Model.name, PhoneNumber=Model.PhoneNumber})
</div>
PLEASE NOTE: The order form is a rough outline and will need some work to submit the forms data. The form will then submit this data to another ActionResult that will utilise the SMTP namespace(System.Net.Mail):
public ActionResult subOrder(string email, string name,
{
MailMessage mail = new MailMessage("exampleNoReponseEmail#emailexample.com", email);
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = "smtp.google.com";
mail.Subject = "Car payment conformation";
mail.Subject = "Dear, " + name + ", "You want to order car that the client selected . Please read following instructions: Some text";
client.Send(mail);
return View("ConfirmPayment");
}
The confirm email view:
<h1>Email Sent!</h1>
<p>We sent a payment link and instruction for paying on your email. Please check your email.</p>
These links about sending email might also help:
1. Send e-mail via SMTP using C#
2. Sending email in .NET through Gmail
3. https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(v=vs.110).aspx
4. https://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v=vs.110).aspx
I hope this helps!

error to get value from controller

i try to create new room, but roomTypeID always return 1, whats wrong with my code?
i can make a new room type, but i cant insert room facility in my database, because RoomType ID always return 1
this my code..
my controller
public ActionResult NewRoom()
{
ViewBag.hotel = _hotelService.GetByID(_HotelID).HotelName;
List<ShowEditRoomViewModel> showEditRoomViewModel = _roomTypeService.showNewRooms();
return View(showEditRoomViewModel.FirstOrDefault());
}
[HttpPost]
public ActionResult NewRoom(FormCollection typeRoom)
{
_roomTypeService.NewRoom(_HotelID, typeRoom["RoomTypeName"], typeRoom["RoomTypeDescription"]);
List<string> IDs = typeRoom["FacilityIDs"].Split(',').ToList();
List<int> FacilityIDs = new List<int>();
foreach (string ID in IDs)
{
FacilityIDs.Add(Convert.ToInt32(ID));
}
_roomTypeService.UpdateFacilityInRooms(FacilityIDs, Convert.ToInt32(typeRoom["RoomTypeID"]));
return NewRoom();
}
my service
public void UpdateFacilityInRooms(List<int> FacilityIDs, int RoomTypeID)
{
List<HotelRoomFacility> hotelRoomFacilities = _HotelRoomFacilityRopository.AsQueryable().Where(f => f.RoomTypeID == RoomTypeID).ToList();
foreach (int newRoomFacility in FacilityIDs)
{
if (hotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacility).Count() == 0)
{
HotelRoomFacility facility = new HotelRoomFacility
{
RoomFacilityID = newRoomFacility,
RoomTypeID = RoomTypeID
};
_HotelRoomFacilityRopository.Add(facility);
}
}
_HotelRoomFacilityRopository.CommitChanges();
}
my view model
public class ShowEditRoomViewModel
{
public int RoomTypeID { get; set; }
public string RoomTypeName { get; set; }
public string RoomTypeDescription { get; set; }
public List<FaciliyInRoom> facilityinRoom { get; set; }
}
my view
#model XNet.Repository.Model.ShowEditRoomViewModel
#{
ViewBag.Title = "NewRoom";
}
<h2>New Room</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Isikan Data</legend>
<div>
#Html.Label("Hotel Name")
</div>
<div>
#ViewBag.hotel
</div>
<br />
<div>
#Html.HiddenFor(model => model.RoomTypeID)
</div>
<br />
<div>
#Html.Label("Room Type Name")
</div>
<div>
#Html.EditorFor(model => model.RoomTypeName)
#Html.ValidationMessageFor(model => model.RoomTypeName)
</div>
<br />
<div>
#Html.Label("Room Type Description")
</div>
<div>
#Html.TextAreaFor(model => model.RoomTypeDescription)
#Html.ValidationMessageFor(model => model.RoomTypeDescription)
</div>
<br />
<table>
<thead>
<tr>
<th>Facility Name</th>
<th> is available</th>
</tr>
</thead>
<tbody>
#foreach (var facility in Model.facilitiesInRoom)
{
<tr>
<td>
#(facility.RoomFacilityName)
</td>
<td style="text-align:center;">
<input type="checkbox" #(facility.RoomFacilityAvailable ? " checked=checked" : null) name="FacilityIDs" value="#facility.RoomFacilityID" />
</td>
</tr>
}
</tbody>
</table>
<br />
<p>
<input type="submit" value="Save" />
<input style="width:100px;" type="button" title="EditHotelDetail" value="Back to Detail" onclick="location.href='#Url.Action("Room", "Hotel") '" />
</p>
</fieldset>
}
My method
public List<ShowEditRoomViewModel> showNewRooms()
{
List<RoomType> roomTypes = (from d in _RoomTypeRepository.All()
select d).ToList();
List<ShowEditRoomViewModel> showEditRoomViewModel = new List<ShowEditRoomViewModel>();
foreach (RoomType roomType in roomTypes)
{
showEditRoomViewModel.Add(new ShowEditRoomViewModel
{
RoomTypeID = roomType.RoomTypeID,
facilitiesInRoom = LoadFacilityInRoom()
});
}
return showEditRoomViewModel;
}
can someone tell me, where is my mistake??
thanks
When you are inserting RoomtypeId in Database, you are using ExecuteNonQuery() method, It will always return 1 whenever you insert a new record in it,
If you are using stored procedure for inserting,you can use
select Scope_identity()
after insertion.

Resources