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

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

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

How can i save changes made to the database

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

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!

how to convert formcollection to model in mvc

Is it possible to convert formcollection to a 'model' known?
[HttpPost]
public ActionResult Settings(FormCollection fc)
{
var model=(Student)fc; // Error: Can't convert type 'FormCollection' to 'Student'
}
NOTE : for some reasons i can't use ViewModel instead.
Here is my code VIEW: Settings.cshtml
#model MediaLibrarySetting
#{
ViewBag.Title = "Library Settings";
var extensions = (IQueryable<MediaLibrarySetting>)(ViewBag.Data);
}
#helper EntriForm(MediaLibrarySetting cmodel)
{
<form action='#Url.Action("Settings", "MediaLibrary")' id='MLS-#cmodel.MediaLibrarySettingID' method='post' style='min-width:170px' class="smart-form">
#Html.HiddenFor(model => cmodel.MediaLibrarySettingID)
<div class='input'>
<label>
New File Extension:#Html.TextBoxFor(model => cmodel.Extention, new { #class = "form-control style-0" })
</label>
<small>#Html.ValidationMessageFor(model => cmodel.Extention)</small>
</div>
<div>
<label class='checkbox'>
#Html.CheckBoxFor(model => cmodel.AllowUpload, new { #class = "style-0" })<i></i>
<span>Allow Upload.</span></label>
</div>
<div class='form-actions'>
<div class='row'>
<div class='col col-md-12'>
<button class='btn btn-primary btn-sm' type='submit'>SUBMIT</button>
</div>
</div>
</div>
</form>
}
<tbody>
#foreach (var item in extensions)
{
if (item != null)
{
<tr>
<td>
<label class="checkbox">
<input type="checkbox" value="#item.MediaLibrarySettingID"/><i></i>
</label>
</td>
<td>
<a href="javascript:void(0);" rel="popover" class="editable-click"
data-placement="right"
data-original-title="<i class='fa fa-fw fa-pencil'></i> File Extension"
data-content="#EntriForm(item).ToString().Replace("\"", "'")"
data-html="true">#item.Extention</a></td>
</tr>
}
}
</tbody>
CONTROLLER:
[HttpPost]
public ActionResult Settings(FormCollection fc)//MediaLibrarySetting cmodel - Works fine for cmodel
{
var model =(MediaLibrarySetting)(fc);// Error: Can't convert type 'FormCollection' to 'MediaLibrarySetting'
}
data-content and data- attributes are bootstrap popover.
Another approach in MVC is to use TryUpdateModel.
Example:
TryUpdateModel or UpdateModel will read from the posted form collection and attempt to map it to your type. I find this more elegant than manually mapping the fields by hand.
[HttpPost]
public ActionResult Settings()
{
var model = new Student();
UpdateModel<Student>(model);
return View(model);
}
Nice question!
Had same in the quest of making a universal base controller, model independent. Thanks to many people, the last one was #GANI, it's done.
Type ViewModelType is set in subclassed controller to anything you want.
public ActionResult EatEverything(FormCollection form)
{
var model = Activator.CreateInstance(ViewModelType);
Type modelType = model.GetType();
foreach (PropertyInfo propertyInfo in modelType.GetProperties())
{
var mykey = propertyInfo.Name;
if (propertyInfo.CanRead && form.AllKeys.Contains(mykey))
{
try
{
var value = form[mykey];
propertyInfo.SetValue(model, value);
}
catch
{
continue;
}
}
}
now that everything you received from an unknown form is in your real model you can proceed to validation from this post https://stackoverflow.com/a/22051586/7149454
You can try this way
public ActionResult Settings(FormCollection formValues)
{
var student= new Student();
student.Name = formValues["Name"];
student.Surname = formValues["Surname"];
student.CellNumber = formValues["CellNumber"];
return RedirectToAction("Index");
}
maybe it's too late, but maybe it will be useful for someone )
https://www.nuget.org/packages/tidago.apofc
Auto converter formcollection to object.
TestReadonlyModel resultObject = new TestReadonlyModel();
new ObjectPopulator().Populate(HttpContext.Request.Form, resultObject);

How to get data from partial in form

I have
ASP.NET MVC Form in popup with some controls and partial (data grid) with his own Model.
here is popup:
<div id="AddEditDialog" class="none">
#using (Ajax.BeginForm("Save", "Templates", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "AddEditPlaceHolder",
OnSuccess = "OnSaveSuccess",
HttpMethod = "Post"
}))
{
<div>
<div id="AddEditPlaceHolder"></div>
<div id="PopupButtons" class="btn-holder-centered">
<input type="submit" value="Save" name="SaveButton" />
<input type="button" value="Cancel" name="SaveCancelButton" id="CancelEditHandler" />
</div>
</div>
}
</div>
here is form which I render in AddEditPlaceHolder via js:
#model TemplatesViewModel
<div class="form-field-plain overflow">
<div class="forRow narRow float-left">
#Html.LabelFor(x => x.Revocable)
#Html.CheckBoxFor(x => x.Revocable)
</div>
</div>
<div class="form-field-plain overflow">
<div class="forRow narRow float-left">
#Html.LabelFor(x => x.HtmlTemplate)
#Html.TextAreaFor(x => x.HtmlTemplate)
</div>
</div>
#Html.Partial("_VariablesGridView", Model.Variables)
_VariablesGridView.cshtml:
#model List<TemplateVariableViewModel>
<table id="TemplateVariablesGrid">
<thead>
<tr>
<td>Tag/Code</td>
<td>Prompt</td>
<td>Action</td>
</tr>
</thead>
<tbody>
#foreach (var i in Model)
{
<tr>
<td>
#Html.TextBox("txtTag", #i.Tag, new {})
</td>
<td>
#Html.TextBox("txtPrompt", #i.Prompt, new { })
</td>
<td>
#Html.HiddenFor(x => x.First(s => s.Id == #i.Id).Id)
<label class="delete-variable">delete</label>
</td>
</tr>
}
</tbody>
</table>
<br />
<input type="button" name="btnAddTemplateVariable" value="add new variable"/>
<br />
My problem is :
in Controller 'save form' method public ActionResult Save(TemplateViewModel model)
my model contains all data from form but TemplateViewModel.Variables is empty
Is there any way to fill it in there?
Models:
public class TemplateViewModel
{
public int Id { get; set; }
public string HtmlTemplate { get; set; }
public List<TemplateVariableViewModel> Variables { get; set; }
}
public class TemplateVariableViewModel
{
public int Id { get; set; }
public string Tag { get; set; }
public string Prompt { get; set; }
}
I believe it is because the ASP.Net MVC binding is not putting these fields in context, have a look at your field names delivered to the browser, what is txtTag prefixed by when it gets to the browser and what is is after you do the following:
#Html.Partial("_VariablesGridView", Model)
_VariablesGridView.cshtml:
#model TemplatesViewModel
...
#for (int i = 0; i < Model.Variables.Count; i++)
#Html.TextBox("txtTag", #Model.Variables[i].Tag, new {})
Forgive me if this fails miserably (again), I'm shooting from the hip.

Resources