How to create view for given model - asp.net-mvc

I am new to asp .net mvc 4.0. i have given model. i am not getting how can i create view for model. I am facing problem at IList JournalEntries. other entry i am able to do.
public class Journal : BaseClass
{
public virtual string VoucherNo { get; set; }
public virtual DateTime VoucherDate { get; set; }
public string VoucherDateView {
get
{
return VoucherDate.ToShortDateString();
}
}
public IList<JournalEntry> JournalEntries { get; set; }
public IList<Ledger> Accounts { get; set; }
public double TotalAmount
{
get
{
double sum = 0;
if (JournalEntries != null && JournalEntries.Count>0)
foreach (var journal in JournalEntries)
sum = journal.Principal + journal.Interest+sum;
return sum;
}
}
}
I have tried below view but add entry doesn't works.
#model Sms.CoreSociety.Journal
#{
ViewBag.Title = "Create";
}
#{
string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
<script type="text/javascript">
$(document).ready(function () {
$('#document').validate();
$("#VoucherDate").mask("99/99/9999", { placeholder: " " });
function entryVm(entries) {
var self = this;
self.entryList = ko.observableArray(entries);
self.entry = ko.observable();
self.rowClick = function(entry1) {
alert("Delete alert");
self.dispatchList.remove(entry1);
};
self.addEntry = function() {
alert("Add alert");
this.entryList.push({ AccountName_AccountHead: "", DebitCredit: "", Principal: "0.0", Interest: "0.0", Narration: ""});
};
}
var models = #Html.Raw(Json.Encode(Model.JournalEntries)) ;
ko.applyBindings(new entryVm(models));
});
</script>
#using (Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "class", "form-horizontal" }, { "id", "document" } }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span1">
<label>Voucher No</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.VoucherNo)
</div>
</div>
<div class="row">
<div class="span1">
<label>Voucher Date</label>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.VoucherDate, "{0:dd/MM/yyyy}", new Dictionary<string, object>() { { "class", "required" } })
</div>
</div>
<div class="row">
<div class="span1">
<label>Amount</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.TotalAmount)
</div>
</div>
<input type="submit" value="Save" class="btn" id="submit"/>
#if (Model.Id != new Guid())
{
<div style="float: right">
<a class="btn btn-danger" href='#Url.Action("Delete")/#Model.Id' aria-hidden="true">Delete</a>
</div>
}
</fieldset>
}
<h4>Journal Entry</h4>
<p >Entry for<span data-bind="text: entryList().length"> </span> entry(s)</p>
<button data-bind="click: addEntry" class="btn">Add Record</button>
<table>
<tbody data-bind="template: { name: 'entryRowTemplate', foreach: entryList }"></tbody>
</table>
<script type="text/html" id="entryRowTemplate">
<tr>
<td>AccountName_AccountHead: \$ <input data-bind="value: AccountName.AccountHead"/> </td>
<td>DebitCredit: \$ <input data-bind="value: DebitCredit"/></td>
<td>Principal: \$ <input data-bind="value: Principal"/></td>
<td>Interest: \$ <input data-bind="value: Interest"/></td>
<td>Narration: \$ <input data-bind="value: Narration"/></td>
<td>Delete</td>
</tr>
</script>
below is my Journal controller
using System;
using System.Linq;
using System.Web.Mvc;
using Sms.CoreSociety;
using System.Collections.Generic;
namespace SmsModernUI.Controllers
{
public class JournalController : BaseController
{
//
// GET: /AccountGroup/
public ActionResult Index()
{
var journals = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo);
return View(journals);
}
public ActionResult Create(Guid id)
{
if (id == new Guid())
{
var journal = new Journal();
string lastvoucherno = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo).Last().VoucherNo;
journal.VoucherNo = (int.Parse(lastvoucherno) + 1).ToString();
journal.VoucherDate = System.DateTime.Now;
journal.JournalEntries = new List<JournalEntry>();
journal.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal);
}
var journal1 = Repository.Get<Journal>(id);
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == id);
journal1.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Journal journal)
{
if (journal.Id == new Guid())
{
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
else
{
Journal jr = Repository.Get<Journal>(journal.Id);
var entries = Repository.GetAll<JournalEntry>(x=>x.Journal.Id == journal.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
return RedirectToAction("Index");
}
public ActionResult Index1()
{
Journal journal1 = Repository.Get<Journal>(new Guid("7A6EEBBC-2F3A-4A27-ACF8-A1D40115A68F"));
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == journal1.Id);
journal1.Accounts = Repository.GetAll<Ledger>();
return View(journal1);
}
public ActionResult Delete(Guid id)
{
Journal jr = Repository.Get<Journal>(id);
var entries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == jr.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var result = Repository.Delete(jr);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Create1(Journal journal)
{
var temp = journal;
return RedirectToAction("Create",journal.Id);
}
}
}

Views are not genereted from models. You need Controller Action method to pass your model to View.
public ActionResult()
{
var model = new Journal
{
//**define here value of model's properties, that you need in View
}
return View(model);
}
EDITED: After your addition.
I would devide it into two parts. Create ViewModel and pass it from View To Controller.
public JurnalViewModel
{
public Journal journal {get; set;}
public IList<JournalEntry> JournalEntries {get; set;}
}
Than in Create action first create journal and after foreach JournalEntries in model create new JournalEntry.
EDITED 2 To your comment. Quick sample:
[HttpPost]
public ActionResult Create (JurnalViewModel model)
{
var journal = new Journal();
db.Journals.Add(journal);
journal.name = model.journal.name
.....
//**some code
db.SaveChanges()
foreach(var item in model.JournalEntries )
{
var entry = new JournalEntry()
db.JournalEntries .Add(entry);
entry.property = item.property;
....
//**some code
db.SaveChanges()
}
}

Your problem is that you have no class constructor for JournalEntries.
public Journal()
{
JournalEntries = new List<JournalEntry>();
Accounts = new List<Ledger>();
}

Right click to your Action method inside controller and click add view then check create strongly typed-view checkbox then choose your desired model from dropdown in displayed dialogue box

Related

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

Displaying List of Uploaded Files

I have a form where users can upload files and then view a list of their uploads. I'm running into two issues:
List of files isn't appearing when page loads. The SQL Query is valid.
When user uploads a file, a NullReferenceException because the file list model isn't being loaded. I'm not sure how to pass this model into view after the upload. Any advice is greatly appreciated.
Controller for fetching list of datasets is below. The controller for uploading datasets is different, of course, but it accepts an HttpPostedFileBase and a datasetName. It only returns ViewBag.error/ViewBag.message.
public ActionResult upload(DatasetViewModel model)
{
List<DatasetDetail> model2 = new List<DatasetDetail>();
var connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionstring))
try
{
// Your code
con.Open();
using (SqlCommand cmd = new SqlCommand("", con))
{
cmd.CommandText = "SELECT datasetid, datasetname, timestamp FROM datasets WHERE userid = #userid";
cmd.Parameters.Add("#userid", SqlDbType.Text);
cmd.Parameters["#userid"].Value = System.Web.HttpContext.Current.User.Identity.GetUserId();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var u = new DatasetDetail();
u.datasetid = reader["datasetid"].ToString();
u.dataset = reader["datasetname"].ToString();
/* u.timestamp = Convert.ToDateTime(reader["TIMESTAMP"]);*/
model2.Add(u);
}
}
}
catch
{
// Catch exception
}
finally
{
// Close the connection
con.Close();
}
model.datasetlist = model2;
return View(model);
}
View:
#model WebApplication12.Models.DatasetViewModel
<div style="width: 320px;">
<h2>Manage Datasets</h2>
Download Excel Template
#using (Html.BeginForm("upload", "Dashboard", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label>Dataset Name:</label>
<br />
<input type="text" id="datasetname" name="datasetname" />
</div>
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-block" />
</div>
}
</div>
<div id="response"></div>
#if (ViewBag.Message != null)
{
<div class="alert alert-success" role="alert">#Html.Raw(ViewBag.Message)</div>
}
#if (ViewBag.Error != null)
{
<div class="alert alert-error" role="alert">#Html.Raw(ViewBag.Error)</div>
}
<div>
#foreach (var u in Model.datasetlist)
{
<b>u.dataset</b>
}
</div>
Relevant Models:
public class DatasetViewModel
{
public List<DatasetDetail> datasetlist { get; set; }
}
public class DatasetDetail
{
public string datasetid { get; set; }
public string dataset { get; set; }
/* public DateTime timestamp { get; set; }*/
}

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!

Sessions in MVC 5 asp.net

I am doing a project about an Chinese food ordering system, and I am wanting show selected items in a view on another page. I am trying to use sessions, but I keep getting different errors, like "The model item passed into the dictionary is of type" and "object reference is not set to an instance of an object". How can I select the data, and show them in a different view? The project is linked up to a database, the DishID and other instances should be connected through the database.
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KinaRest.Models;
using KinaRest.View_Models;
using KinaRest.Infrastructure;
namespace KinaRest.Controllers
{
public class TakeawayController : Controller
{
private Basket basket = new Basket();
[ChildActionOnly]
public ActionResult BasketItemsList()
{
Basket basket = new Basket();
return View("_Basket", basket.Items);
}
// GET: /Takeaway/
private ChinaContext db = new ChinaContext();
[HttpGet]
public ActionResult Index()
{
return View(db.Dish.ToList());
}
[HttpPost]
public ActionResult Index(BasketItem basketItem)
{
//Repository repository = new Repository();
if (Session["Basket"] == null)
{
Session["Basket"] = new Basket();
}
else
{
basket = (Basket)Session["Basket"];
}
basket.AddItem(basketItem);
return View("Test");
}
}
}
Model 1: Basket
namespace KinaRest.Infrastructure
{
public class Basket
{
private List<BasketItem> items = new List<BasketItem>();
public List<BasketItem> Items { get { return items; } }
public void AddItem(BasketItem bi) {
items.Add(bi);
}
}
}
Model 2: BasketItem
namespace KinaRest.Infrastructure
{
public class BasketItem
{
public int DishId {get; set; }
public int Number { get; set; }
public decimal Price { get; set; }
}
}
In this view, we are trying to collect the data, such as the ID, the quantity(number) and price with a form:
#model IEnumerable<KinaRest.Models.Dish>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div class="form-group">
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.DishId)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Title)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Price)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Description)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Type.Type1)
</div>
<img src="#Url.Content("~/content/images/" + item.Image)" />
#Html.EditorFor(model => item.Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => item.Number, "", new { #class = "text-danger" })
<input type="submit" value="Tilføj" class="btn btn-default" />
}
}
</div>
In this view, we are trying to access the sessions data:
#model List<KinaRest.Infrastructure.BasketItem>
#{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Test</h2>
<ul>
#foreach (var item in Model)
{
<li>
#Html.DisplayFor(modelItem => item.Number)
</li>
}
</ul>
and yes, I am new to MVC and I am still learning. Hope you guys can help.
[HttpGet]
public ActionResult Order(int id)
{
Dish dish = db.Dish.Single(d=> d.DishId == id); //database call here
BasketItem basketItem = new BasketItem(){DishId = dish.?, Number = dish.?, Price = dish.Price }; // create a new BasketItem
Basket basket; //create reference outside if block
//Repository repository = new Repository();
if (Session["Basket"] == null)
{
basket = new Basket();
Session["Basket"] = basket;
}
else
{
basket = (Basket)Session["Basket"];
}
basket.AddItem(basketItem);
return View("Test", basket.Items); //or return View(((Basket)Session["Basket"]).Items); // give the view the data
}
take out the class field basket. As far as i know the controller is instanciated every time when a request is to be processed
View for ordering
#model IEnumerable<KinaRest.Models.Dish>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<table>
<tr><th></th><th>Dish</th><th></th></tr>
#foreach(var item in Model)
{
<tr><td><img src="#Url.Content("~/content/images/" + item.Image)" /></td><td>#html.displayfor(item => item.Name)</td><td>#Html.ActionLink("Add", "Order", "TakeAway", new {id = item.DishId})</td></tr>
}
</table>

MVC 4 Model Binding to Radio button list on Submit

My project is MVC 4 with jquery mobile. I'm trying to figure out how to fill my model with data on submit with the following:
From a hidden value that will be populated on the get request
Checked Radio button value from a list on the view
Here is my Model:
public class ResultsModel
{
[Display(Name = "PatientFirstName")]
public string PatientFirstName { get; set; }
[Display(Name = "PatientLastName")]
public string PatientLastName { get; set; }
[Display(Name = "PatientMI")]
public string PatientMI { get; set; }
public List<QuestionModel> QuestionList = new List<QuestionModel>();
}
public class QuestionModel
{
public string Question { get; set; }
public int QuestionID { get; set; }
public int AnswerID { get; set; }
}
It has a collection of questions that is filled with data on the get request. Here is the controller code:
public class ResultsController : Controller
{
//
// GET: /Results/
public ActionResult Index()
{
if (Request.IsAuthenticated)
{
ResultsModel resultsModel = new ResultsModel();
//Get data from webservice
myWebService.TestForm inrform;
var service = new myWebService.myService();
testform = service.TestForm(id);
if (testform != null)
{
//Render the data into results data model
int count = 1;
string text = string.Empty;
foreach (myWebService.Question questiontext in testform.QuestionList)
{
QuestionModel newquestion = new QuestionModel();
text = "Question " + count + ": " + questiontext.text;
if (questiontext.text != null)
{
newquestion.Question = text;
newquestion.QuestionID = questiontext.id;
}
resultsModel.QuestionList.Add(newquestion);
count += 1;
}
}
else
{
//Error
}
return View(resultsModel);
}
// Error
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult Index(ResultsModel model,FormCollection fc)
{
if (fc["Cancel"] != null)
{
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
in the post action, the model.QuestionList is always empty. Here is my View:
#model Models.ResultsModel
#{
ViewBag.Title = Resources.Account.Results.Title;
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<li data-role="fieldcontain">
#Html.LabelFor(m => m.INRTestDate)
#Html.EditorFor(m => m.INRTestDate)
#Html.ValidationMessageFor(model => model.INRTestDate)
</li>
<li data-role="fieldcontain">
#Html.LabelFor(m => m.INRValue)
#Html.TextBoxFor(m => m.INRValue)
</li>
<li>
#for (int i = 0; i < Model.QuestionList.Count; i++)
{
<div data-role="label" name="question" >
#Model.QuestionList[i].Question</div>
#Html.HiddenFor(m => m.QuestionList[i].QuestionID)
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain" >
<input id="capture_type_yes" name="answer_type" type="radio" data-theme="c" value="1" />
<label for="capture_type_yes" >
Yes</label>
<input id="capture_type_no" name="answer_type" type="radio" data-theme="c" value="0" />
<label for="capture_type_no">
No</label>
<input id="capture_type_na" name="answer_type" type="radio" data-theme="c" value="2" />
<label for="capture_type_na">
Not Applicable</label>
</fieldset>
</div> }
<label for="textarea-a">
Comments</label>
<textarea name="textarea" id="textarea-a"> </textarea>
<fieldset class="ui-grid-a">
<div class="ui-block-a">
<button type="submit" name="Submit" data-theme="c">Submit</button></div>
<div class="ui-block-b">
<button type="submit" name="Cancel" data-theme="b" class="cancel">Cancel</button></div>
</fieldset>
</li>
In the for each code above, my model.Questionlist collection is not being updated. I also need to figure out how I can tie the radio button click (Yes,No or Not Applicable) to the AnswerID property of my model.Questionlist collection
It actually ended up being this line:
public List<QuestionModel> QuestionList = new List<QuestionModel>();
I needed the get/set to initialize
public List<QuestionModel> QuestionList { get; set; }
Please Can You Add Code after
[AllowAnonymous]
[HttpPost]
public ActionResult Index(ResultsModel model,FormCollection fc)
{
if (fc["Cancel"] != null)
{
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
This would be a good post if you finish your code.
MVC5 Bind a LIST for Radio Button with Razor
Create a class RadioList anywhere in the program
public class RadioList
{
public int Value { get; set; }
public string Text { get; set; }
public RadioList(int Value, string Text)
{
this.Value = Value;
this.Text = Text;
}
}
In your Controller
List<RadioList> Sexes = new List<RadioList>();
Sexes.Add(new RadioList(1, "Male"));
Sexes.Add(new RadioList(2, "Female"));
Sexes.Add(new RadioList(3, "Other"));
ViewBag.SexeListe = Sexes;
In the Razor view (replace model.Sexe by the value in your database/model field
#foreach (RadioList radioitem in ViewBag.SexeListe) {
#Html.RadioButtonFor(model => model.Sexe, #radioitem.Value) #Html.Label(#radioitem.Text)
}

Resources