How to save image in database and display it into Views in MVC 5? - asp.net-mvc

I have a table like following
CREATE TABLE [dbo].[Movies] (
[fname] NVARCHAR(50) NULL,
[lname] NVARCHAR(50) NULL,
[MoviePoster] VARCHAR (50) NULL,
how to save image to movie poster field and how to view it

[MoviePoster] [varbinary](max) NULL
-- You have to insert image as a BLOB
-- Insert blob script :
INSERT INTO [Movies](MoviePoster)
VALUES (SELECT * FROM OPENROWSET (BULK 'your img url', SINGLE_BLOB))
--Display image in views:
<img src='data:image/jpeg;base64, <--data from db-->' />

How about saving movie poster on your server let's say:
/content/images/movieposters/thearrival.jpg
and storing in MoviePoster field only the filename thearrival.jpg
I personally prefer this approach because if let's say your database will grow and you will have more visitors ...well, you will be able to move all your movie posters to a different server and free up a lot of load from application server.

Creat an "Images" folder in Solution explorer.
Create an ADO.NET Entity Data Model (in this example is "Database1Entities")
Home Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace test2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
Database1Entities db = new Database1Entities();
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath =Server.MapPath("~/images/"+ ImageName);
// save image in folder
file.SaveAs(physicalPath);
//save new record in database
tblA newRecord = new tblA();
newRecord.fname = Request.Form["fname"];
newRecord.lname = Request.Form["lname"];
newRecord.MoviePoster = ImageName;
db.tblAs.Add(newRecord);
db.SaveChanges();
}
//Display records
return RedirectToAction("../home/Display/");
}
public ActionResult Display()
{
return View();
}
}
}
Index View
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div>
First name<br />
#Html.TextBox("fname") <br />
Last name<br />
#Html.TextBox("lname") <br />
Image<br />
<input type="file" name="file" id="file" style="width: 100%;" /> <br />
<input type="submit" value="Upload" class="submit" />
</div>
}
DisplayView
#{
ViewBag.Title = "Display";
}
#{
test2.Database1Entities db = new test2.Database1Entities();
}
#using (Html.BeginForm())
{
<table border="1">
<thead>
<tr>
<th>Image</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
#foreach (var item in db.tblAs)
{
<tr>
<td><img src="~/images/#item.imageUrl" width="100" height="100" /> </td>
<td>#item.fname</td>
<td>#item.lname</td>
</tr>
}
</tbody>
</table>
}
The OutPut will be a table with viewed image from the database

Actually you can store the image on Db as well. You don't need to keep it on the server as a file if you don't want to (if you have lots of movies it would be a problem to manage).
If you are using SQL Server there is a "image" data type. If you are using MySql you should use BLOB.
I am using MVC, so:
The Model (partial code) (while in SqlServer you will declare image, inside the model the type will be byte[]:
public byte[] PersonImage { get; set; }
Inside the same model you are going to need a method to retrieve the path:
public string GetPicture()
{
if (PersonImage == null)
{
return null;
}
var base64Image = System.Convert.ToBase64String(PersonImage);
return $"data:{ImageContentType};base64,{base64Image}";
}
The create action inside the controller (The action declaration will need to receive an IFormFile PersonImage), on my case I am handling the image upload on the register action of my controller (Some of the controller code has been taken off to be more concise):
public async Task<IActionResult> Register(RegisterViewModel model, Client client, Employee employee, Person person, IFormFile PersonImage, string returnUrl = null)
if (PersonImage != null)
{
using (var stream = new MemoryStream())
{
await PersonImage.CopyToAsync(stream);
person.PersonImage = stream.ToArray();
person.ImageContentType = PersonImage.ContentType;
}
}
_context.Add(person);
await _context.SaveChangesAsync();
And now the view, you need to add the enctype to the form:
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form asp-route-returnUrl="#ViewData["ReturnUrl"]" method="post" enctype="multipart/form-data">
<h2 class="text-center font-weight-bold">Create a new account.</h2>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="#person.PersonImage" class="control-label"></label>
<input type="file" asp-for="#person.PersonImage" class="form-control" />
<span asp-validation-for="#person.PersonImage" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-default">Register</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
Again, I took off most of the code to get a better and concise example. I had a hard time to find this when I was trying to put some images to the Db.

[HttpPost]
public ActionResult AddEmployee(HttpPostedFileBase file)
{
using(DbEntities DB = new DbEntities())
{
TblImage tblimg=new TblImage();
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("~/Data/EmployeeProfileImage/" + fileName));
tblimg.image = "~/Data/EmployeeProfileImage/" + fileName;
}
DB.TblImages.Add(tblimg);
DB.SaveChanges();
}
return View();
}

INDEX
#{
ViewBag.Title = "Index";
}
<link href="~/bootstrapp/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrapp/js/bootstrap.min.js"></script>
<style>
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<h2>Index</h2>
#using (Html.BeginForm("Index", "Candidate", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="container">
<table>
<tr><td colspan="2" style="width:800px;height:50px">candidate</td></tr>
<tr><td>#*<label>Id</label><input type="number" name="candidateID" />*#</td></tr>
<tr>
<td style ="width:10px;height:10px">
<label>Name</label> <input type="text" name="Name" />
</td>
<td style="width:80px;height:50px"><label>Binary Image</label>
<input type="file" name="file1" id="file1" style="width: 100%;" /> <br />
</td>
</tr>
<tr>
<td>
<label>Address</label> <input type="text" name="address" />
</td>
<td>
<label>Path Image</label> <input type="file" name="file2" id="file2" style="width: 100%;" />
</td>
</tr>
<tr>
<td>
<label>JobProfile</label> <input type="text" name="JobProfile" />
</td>
<td>
<label>Email</label> <input type="text" name="email" />
</td>
</tr>
<tr><td>
<label>Phone No.</label> <input type="number" name="phone" />
</td><td ><input type="submit" value="Submit"/></td></tr>
</table>
</div>
}
#Html.Partial("~/Views/Candidate/detail.cshtml")
DETAIL
#*#model List< angularmvcdemo.CandidateDetail>*#
#using angularmvcdemo.Models;
<link href="~/bootstrapp/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrapp/js/bootstrap.min.js"></script>
<style>
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
#{
modeldataEntities db = new modeldataEntities();
//angularmvcdemo.modeldataEntities db = new angularmvcdemo.modeldataEntities();
}
<table>
<tr><td colspan="2" style="width:800px;height:50px">candidate</td></tr>
#foreach(var detail in db.CandidateDetails){
<tr>
<td style="width:10px;height:10px">
<label>Name</label>#detail.Name
#*<input type="text" name="Name" />*# </td>
<td> binary image
#if (detail.BinaryPhoto != null)
{ var base64 = Convert.ToBase64String(detail.BinaryPhoto);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
<img src='#imgsrc' style="max-width:100px;max-height:100px" />
}
else { <img src="~/img/avatar-default.jpg" style="max-width:100px;max-height:100px" /> } </td>
</tr>
<tr>
<td>
<label>Address</label> #detail.address </td>
<td><label>path image</label>
#if(#detail.PathPhoto!=null){ <img src="#detail.PathPhoto" width="100" height="100" />
}else{ <img src="~/img/avatar-default.jpg" style="max-width:100px;max-height:100px" /> } </td>
</tr>
<tr>
<td>
<label>JobProfile</label>#detail.JobProfile </td>
<td>
<label>Email</label> #detail.email </td>
</tr>
<tr><td></td><td><label>Phone No.</label>
#detail.phone</td><</tr>
}
</table>

Related

.Net 6 - Passing a radio button selected table row to a controller

I really feel like this should be easy but I’m thinking it may have changed with .Net 6. I can pass values to my controller with the input “name=’name’” but for some reason I cannot get any values from my model into my controller. I am trying to POST my row values to the controller. I am using an enumerable. I’m not sure if I should be using a or not. Another thing is how should I be populating my table row from a loop of the model. I thought using #Html. Was for older .net and tag helpers are the new way but I couldn’t get any to work populating my rows.
<form method="post">
<div id="tblPullParts" class="container justify-content-center mt-3">
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th >Order #</th>
<th >Item</th>
<th >Description</th>
<th >Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var p in Model)
{
<tr>
<td><input type="radio" id="radio" name="radio"
value="#Html.DisplayFor(item => p.PartID)" /></td>
#*<td><input asp-for="Selected" type="radio" value="Selected" /></td>*#
<th scope="row">#Html.DisplayFor(item => p.PartID)</th>
<td>#Html.DisplayFor(item => p.Name)</td>
<td>#Html.DisplayFor(item => p.ItemLocation)</td>
<td>#Html.DisplayFor(item => p.PartGroup)</td>
<td>#Html.DisplayFor(item => p.Description)</td>
<td>
<input type="text" asp-for="#p.Name" id="txtNameN" />
</td>
</tr>
}
</tbody>
</table>
#*<input type="text" id="#Model[0].Name" />*#
<input type="text" id="txtName" name="txtName" value="" />
</div>
<div class="text-center">
<button type="submit" class="btn btn-lg btn-success mt-3">Start Pick</button>
</div>
</form>
[HttpPost]
public async Task<IActionResult> Index( PartVM model, string radio, string txtName)
{
if (model?.PartID != 0)
{
return View("UpdatePickQuantity", model);
}
if (!String.IsNullOrWhiteSpace(txtName))
{
}
//Request.QueryString["radio"];
var lstParts = await _ordersService.GetAllParts();
return View(lstParts);
}
#Html.DisplayFor() can only display the value of model, If you want to submit the value, You need to use <input>,Here is a simple demo, I add hidden input in your form to submit the value:
#model List<PartVM>
#{
int i = 0;
}
<form method="post">
<div id="tblPullParts" class="container justify-content-center mt-3">
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th >Order #</th>
<th >Item</th>
<th >Description</th>
<th >Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var p in Model)
{
<tr>
<td><input type="radio" id="radio" name="radio"
value="#Html.DisplayFor(item => p.PartID)" /></td>
#*<td><input asp-for="Selected" type="radio" value="Selected" /></td>*#
<th scope="row">
#Html.DisplayFor(item => p.PartID)
<input type="hidden" asp-for="#p.PartID" name="[#i].PartID">
</th>
<td>
#Html.DisplayFor(item => p.Name)
</td>
<td>
#Html.DisplayFor(item => p.ItemLocation)
<input type="hidden" asp-for="#p.ItemLocation" name="[#i].ItemLocation">
</td>
<td>
#Html.DisplayFor(item => p.PartGroup)
<input type="hidden" asp-for="#p.PartGroup" name="[#i].PartGroup">
</td>
<td>
#Html.DisplayFor(item => p.Description)
<input type="hidden" asp-for="#p.Description" name="[#i].Description">
</td>
<td>
<input type="text" asp-for="#p.Name" name="[#i].Name" id="txtNameN" />
</td>
</tr>
i++;
}
</tbody>
</table>
#*<input type="text" id="#Model[0].Name" />*#
<input type="text" id="txtName" name="txtName" value="" />
</div>
<div class="text-center">
<button type="submit" class="btn btn-lg btn-success mt-3">Start Pick</button>
</div>
</form>
Controller
[HttpPost]
public async Task<IActionResult> Index( List<PartVM> model, string radio, string txtName)
{
//.....
}
Demo:
Your second question can refer to this github issue.
Edit============================
If you want just want to pass the row where radio is selected, you need to js to achieve this. refer to this:
Create a ViewModel
public class PartvmViewModel
{
public int PartID { get; set; }
public string Name { get; set; }
public string ItemLocation { get; set; }
public string PartGroup { get; set; }
public string Description { get; set; }
public string? txtName { get; set; }
}
controller
public IActionResult Display()
{
List<PartvmViewModel> viewmodel = new List<PartvmViewModel>();
//pass data from PartVM to PartvmViewModel
foreach (var item in PartVms)
{
viewmodel.Add(new PartvmViewModel()
{
PartID = item.PartID,
Description = item.Description,
ItemLocation = item.ItemLocation,
Name = item.Name,
PartGroup = item.PartGroup
});
}
return View(viewmodel);
}
[HttpPost]
public IActionResult Display([FromBody]PartvmViewModel model)
{
//because the value of radio is equal to PartID,SO i don't write it as parameter here
//.........
}
View
#model List<PartvmViewModel>
#{
int i = 0;
}
<form method="post">
<div id="tblPullParts" class="container justify-content-center mt-3">
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th >Order #</th>
<th >Item</th>
<th >Description</th>
<th >Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var p in Model)
{
<tr>
<td><input type="radio" name="radio" onclick="Method(this)"
value="#Html.DisplayFor(item => p.PartID)" /></td>
#*<td><input asp-for="Selected" type="radio" value="Selected" /></td>*#
<th scope="row">
#Html.DisplayFor(item => p.PartID)
<input type="hidden" asp-for="#p.PartID" name="[#i].PartID" id="PartID">
</th>
<td>
#Html.DisplayFor(item => p.Name)
</td>
<td>
#Html.DisplayFor(item => p.ItemLocation)
<input type="hidden" asp-for="#p.ItemLocation" name="[#i].ItemLocation" id="ItemLocation">
</td>
<td>
#Html.DisplayFor(item => p.PartGroup)
<input type="hidden" asp-for="#p.PartGroup" name="[#i].PartGroup" id="PartGroup">
</td>
<td>
#Html.DisplayFor(item => p.Description)
<input type="hidden" asp-for="#p.Description" name="[#i].Description" id="Description">
</td>
<td>
<input type="text" asp-for="#p.Name" name="[#i].Name" id="txtNameN" />
</td>
</tr>
i++;
}
</tbody>
</table>
#*<input type="text" id="#Model[0].Name" />*#
<input type="text" id="txtName" name="txtName" value="" />
</div>
<div class="text-center">
<button class="btn btn-lg btn-success mt-3" onclick="Submit()">Start Pick</button>
</div>
</form>
#section Scripts
{
<script>
var Data;
function Method(obj){
this.Data = {
"PartID":$(obj).val(),
"ItemLocation" : $(obj).parent().parent().find('td:eq(2)').find(':input').val(),
"PartGroup" : $(obj).parent().parent().find('td:eq(3)').find(':input').val(),
"Description" : $(obj).parent().parent().find('td:eq(4)').find(':input').val(),
"Name" : $(obj).parent().parent().find('td:eq(4)').find(':input').val(),
}
}
function Submit(){
Data.txtName = $("#txtName").val();
$.ajax({
url : '/Home/Display',
type : 'post',
data : JSON.stringify(Data),
contentType : 'application/json'
});
}
</script>
}
My opinion==========================
Actually, In my opinion, Pass the list of data is ok. Because i notice that you pass the value of radio into the controller, You can just use:
[HttpPost]
public async Task<IActionResult> Index( List<PartVM> model, string radio, string txtName)
{
var item = model.Where(i => i.PartID == int.Parse(radio)).FirstOrDefault();
//.....
}
to get the selected row, It is more easier than using js;
Instead of doing this
<th scope="row">
#Html.DisplayFor(item => p.PartID)
<input type="hidden" asp-for="#p.PartID" name="[#i].PartID" id="PartID">
</th>
I would do something like
<th scope="row">
<p>#p.PartID</p>
<input type="hidden" asp-for="#p.PartID" name="[#i].PartID" id="PartID">
</th>
However, I could be wrong because you are using razor syntax and I am not use to that yet ;)

Asp-action edit not getting the data from razor page

Im trying to submit a form that consist of checkboxes.
When I submit the form I don't get the selected data from the form. I have been trying to use asp-for but I don't understand what I'm doing wrong.
this is my razor page:
#model TheaterReservering.Models.KlantReservering
#{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Reservering voor: #Model.Klant.Naam</h4>
<form asp-action="Edit">
<input type="hidden" asp-for="Klant" />
<table class="table">
<thead>
<tr>
<th>
1
</th>
<th>
2
</th>
<th>
3
</th>
<th>
4
</th>
<th>
5
</th>
<th>
6
</th>
<th></th>
</tr>
</thead>
<tbody>
#{
var count = 0;
}
#foreach (var item in Model.Reserveringen)
{
if ((count % 6) == 0)
{
#:<tr>
}
<td style="text-align:center; vertical-align:middle">
<div class="form-group">
#if (item.KlantId == Model.Klant.Id)
{
<input type="checkbox" asp-for="Reserveringen.ElementAt(count).Bezet" checked />
<br />
<div style="background-color: blue; text-align: center">
<label style="color:white" asp-for="#item.Naam">#item.Naam</label>
</div>
}
else if (item.KlantId == null)
{
<input type="checkbox" asp-for="Reserveringen.ElementAt(count).Bezet" />
<br />
<div style="background-color: green; text-align: center">
<label style="color:white" asp-for="#item.Naam">#item.Naam</label>
</div>
}
else
{
<input type="checkbox" checked disabled />
<br />
<div style=" background-color: red; text-align: center">
<label style="color:white" asp-for="#item.Naam">#item.Naam</label>
</div>
}
</div>
</td>
if ((count % 6) == 5)
{
#:</tr>
}
count++;
}
</tbody>
</table>
<div class="form-group">
<input type="submit" value="Reserveringen vastleggen" class="btn btn-primary" />
</div>
</form>
My controller methode:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Klant,Reserveringen")] KlantReservering klantReservering)
{
if (id != klantReservering.Klant.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
_context.Update(klantReservering);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(klantReservering);
}
and this is the class i created to combine the class Klant with Reservering.
public class KlantReservering
{
public Klant Klant { get; set; }
public List<Reservering> Reserveringen { get; set; }
}
}
As far as I know, the tag helper couldn't work with a model class, it could only work for the model's property.
That means we couldn't use tag helper like this <input type="hidden" asp-for="Klant" />. If we want to achieve model binding in the controller method. I suggest you could add all the property as below:
<input type="hidden" asp-for="#Model.Klant.Id" />
<input type="hidden" asp-for="#Model.Klant.Naam" />
Besides, for the foreach item, tag helper couldn't figure out what the "Reserveringen.ElementAt(count).Bezet" means, we could only use this "#Model.Reserveringen[count].Bezet".
More details, you could refer to below example view:
Notice: Since I don't know your details codes about the Klant and the Reserveringen class, I created a test class in my side which just contains Naam and Id property.
#model CoreNormalIssue.Models.KlantReservering
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*#
#{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Reservering voor: #Model.Klant.Naam</h4>
<form asp-controller="Verify" asp-action="Edit" method="post" asp-route-id="#Model.Klant.Id">
<input type="hidden" asp-for="#Model.Klant.Id" />
<input type="hidden" asp-for="#Model.Klant.Naam" />
<table class="table">
<thead>
<tr>
<th>
1
</th>
<th>
2
</th>
<th>
3
</th>
<th>
4
</th>
<th>
5
</th>
<th>
6
</th>
<th></th>
</tr>
</thead>
<tbody>
#{
var count = 0;
}
#foreach (var item in Model.Reserveringen)
{
<input type="text" asp-for="#item.Bezet" />
if ((count % 6) == 0)
{
#:<tr>
}
<td style="text-align:center; vertical-align:middle">
<div class="form-group">
#if (item.KlantId == Model.Klant.Id)
{
<input type="checkbox" asp-for="#Model.Reserveringen[count].Bezet" checked />
<br />
<div style="background-color: blue; text-align: center">
<label style="color:white" asp-for="#item.Naam">#item.Naam</label>
</div>
}
else if (item.KlantId == null)
{
<input type="checkbox" asp-for="#Model.Reserveringen[count].Bezet" />
<br />
<div style="background-color: green; text-align: center">
<label style="color:white" asp-for="#item.Naam">#item.Naam</label>
</div>
}
else
{
<input type="checkbox" checked disabled />
<br />
<div style=" background-color: red; text-align: center">
<label style="color:white" asp-for="#item.Naam">#item.Naam</label>
</div>
}
</div>
</td>
if ((count % 6) == 5)
{
#:</tr>
}
count++;
}
</tbody>
</table>
<div class="form-group">
<input type="submit" value="Reserveringen vastleggen" class="btn btn-primary" />
</div>
</form>
Result:

How to take data from get and put it to post? Handle input radio type

The form sends a get request and gets the following view
#using System.Linq;
#model List<Searchphone>
<h2 class="search1"></h2>
<form class="priceeconom1" method="post" asp-action="Index" asp-controller="Home">
#foreach (var p in Model)
<table>
{
<tr class="searchdata">
<td class="flight">#p.ColourPhone</td>
<td class="fromtable">#p.TypePhone</td>
<td class="fromtable">#p.SizePhone</td>
<td class="fromtable">#p.PriceLight</td>
<td class="fromtabletime">#p.PriceOk</td>
<td class="totable">#p.PriceHigh</td>
</tr>
}
</table>
All data is generated from multiple linked tables.It is assumed that the user selects one of the "Price" and the form must pass the selected data and price in the Post request.
2)I did it like this
#using System.Linq;
#model List<Searchphone>
<h2 class="search1"></h2>
<form class="priceeconom1" method="post" asp-action="Index" asp-controller="Home">
#foreach (var p in Model)
<table>
{
<tr class="searchdata">
<td class="flight"><input type="text" name="#p.ColourPhone</td>
<td class="fromtable"><input type="text" name="#p.TypePhone</td>
<td class="fromtable"><input type="text" name="#p.SizePhone</td>
<td class="pricelight"><input type="radio" name="price"value="#p.PriceLight.ToString("")"/>#p.PriceLight.ToString("")</td>
<td class="fromtabletime"><input type="radio" name="price"value="#p.PriceOk.ToString("")/>#p.PriceOk.ToString("")</td>
<td class="totable"><input type="radio" name="price"value="#p.PriceHigh.ToString("")/>#p.PriceHigh.ToString("")</td>
<td class="button13"><button type="submit" asp-action="Buy" asp-route-id="#p.PhoneId" asp-controller="Home">Next</button></td>
</tr>
}
</table>
</form>
When I need to go to the next post-form. And I did the next view
#using System.Linq;
#using System;
#model List<Searchphone>
#{
ViewBag.Title = "PhoneId";
}
<h2 class="orderinformation">Order Data</h2>
<form method="post" class="formpass">
<input type="hidden" id="PhoneId"value="#ViewBag.PhoneId" name="PhoneId">
<label for="OrderSurName">Surname</label><br>
<input type="text" placeholder="Enter Surname" name="OrderSurName" required><br>
<label for="OrderName">Имя</label><br>
<input type="text" placeholder="Enter Name" name="OrderName" required><br>
<button type="submit" class="button7">To pay</button>
</form>
Controller
[HttpGet]
public IActionResult Buy(int? id)
{
if (id == null) return RedirectToAction("Index");
ViewBag.PhoneId = id;
return View();
}
[HttpPost]
public string Buy(Order order)
{
context.Orders.Add(order);
context.SaveChanges();
return "Thanks, " + order.OrderName;
}
But I have problem. I got URL:~/Home/Buy/0 and the view with return "Thanks, ". I don`t get the view for input Order Data. Table Order in Database gets default and null values. What is my mistake?
Part 2.Adding to the next question
Controller
[HttpGet]
public IActionResult Buy(int? id, string price)
{
if (id == null) return RedirectToAction("Index");
if(price=="PriceLight.ToString("")")
ViewBag.price=PriceLight.ToString("");
if(price=="PriceOk.ToString("")")
ViewBag.price=PriceOk.ToString("");
if(price=="PriceHigh.ToString("")")
ViewBag.price=PriceHigh.ToString("");
ViewBag.PhoneId = id;
return View();
}
View
#using System.Linq;
#using System;
#model List<Searchphone>
#{
ViewBag.Title = "PhoneId";
}
<h2 class="orderinformation">Order Data</h2>
<form method="post" class="formpass">
<h3> <input type="hidden" name="#ViewBag.price" value="#ViewBag.price" />#ViewBag.price</h3>
<br>
<input type="hidden" id="PhoneId"value="#ViewBag.PhoneId" name="PhoneId">
<label for="OrderSurName">Surname</label><br>
<input type="text" placeholder="Enter Surname" name="OrderSurName" required><br>
<label for="OrderName">Имя</label><br>
<input type="text" placeholder="Enter Name" name="OrderName" required><br>
<button type="submit" class="button7">To pay</button>
</form>
The form is submitted in post method while the return view action only accept a HttpGet request. So, it always hit the HttpPost action since they have the same name.
I tested your codes and find there are some problems in your first view.
[HttpGet]
public IActionResult Buy(int? id)
{
if (id == null) return RedirectToAction("Index");
ViewBag.PhoneId = id;
return View();
}
This action just receive a id parameter. There is no need to submit the whole form. In my opinion, You don’t even need to use forms, just use the < a > tag like below:
#using System.Linq;
#model List<Searchphone>
<h2 class="search1"></h2>
#foreach (var p in Model)
{
<table>
<tr class="searchdata">
<td class="flight"><input type="text" name="#p.ColourPhone" /></td>
<td class="fromtable"><input type="text" name="#p.TypePhone" /></td>
<td class="fromtable"><input type="text" name="#p.SizePhone" /></td>
<td class="pricelight"><input type="checkbox" name="#p.PriceLight.ToString()" /></td>
<td class="fromtabletime"><input type="checkbox" name="#p.PriceOk.ToString()" /></td>
<td class="totable"><input type="checkbox" name="#p.PriceHigh.ToString()" /></td>
<td class="totable"> <a asp-action="Buy" asp-route-id="#p.PhoneId" asp-controller="Home">Next</a></td>
</tr>
</table>
}

How to display one model item per page in ASP.NET Core?

#model OnlineExam.Models.CandidateExam.CandidateItem
#{
ViewData["Title"] = "Index";
var questionList = JsonConvert.DeserializeObject<List<OnlineExam.Models.AdminQuestionModel.QuestionAndAnswers>>(TempData["questionList"].ToString());
//var data = questionList as IEnumerable<OnlineExam.Models.AdminQuestionModel.QuestionAndAnswers>;
var data2 = questionList as List<OnlineExam.Models.AdminQuestionModel.QuestionAndAnswers>; //new stackov
int examAttemptId = Convert.ToInt32(TempData["examAttemptId"].ToString());
TempData.Keep();
}
<h1>Answer Exam</h1>
<h6>Best of luck!!</h6>
<div>
<form enctype="multipart/form-data" asp-action="AnswerExam">
#{
int counter = 0;
}
#for (var i = 0; i < data2.Count(); i++)
{
<table class="table">
<tbody>
<tr class="border-light" style="background-color: lavender">
#{
counter = counter + 1;
}
<td>Question #counter) #data2[i].Question.ToString()</td>
#{
<td>
<input type="hidden" asp-for="candidateExamsList[i].ExamId" value="#data2[i].ExamId" />
<input type="hidden" asp-for="candidateExamsList[i].QuestionId" value="#data2[i].QuestionId" />
<input type="hidden" asp-for="candidateExamsList[i].ExamAttemptId" value="#examAttemptId" />
</td>
}
</tr>
#*<tr class="border-white">
<td>Options : </td>
</tr>*#
<tr class="border-light">
<td>a) #Html.RadioButtonFor(x => x.candidateExamsList[i].OptionSelected, data2[i].OptionOne) #data2[i].OptionOne</td>
</tr>
<tr class="border-light" style="background-color: lavender">
<td>b) #Html.RadioButtonFor(x => x.candidateExamsList[i].OptionSelected, data2[i].OptionTwo) #data2[i].OptionTwo</td>
</tr>
<tr class="border-light">
<td>c) #Html.RadioButtonFor(x => x.candidateExamsList[i].OptionSelected, data2[i].OptionThree) #data2[i].OptionThree</td>
</tr>
<tr class="border-light" style="background-color: lavender">
<td>d) #Html.RadioButtonFor(x => x.candidateExamsList[i].OptionSelected, data2[i].OptionFour) #data2[i].OptionFour</td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
</tbody>
</table>
}
<div class="form-group">
<input type="submit" value="Submit Test" class="btn btn-primary"/>
</div>
</form>
</div>
I have a list of questions in my model and i wish to display each question (model item) on single page and then click next to move on to next question (model item).
How do I achieve that?

Get value of DropDown at Controller while submitting form MVC

This is My View.
#using (Html.BeginForm("uploadimage",
"PatientDocumentsMain",
FormMethod.Post,
new { #Area = "PatientDocument", enctype =
"multipart/form-data" }))
{
<table cellspacing="0" cellpadding="0" class="table table-
striped">
<tr>
<td>
Document Name:<span class="spnError">*</span>
</td>
<td>
<input type="text" id="txtDocumentName" name="DocName"
class="required form-control" />
</td>
</tr>
<tr>
<td class="tdEditDoc">
<span>Document Type:</span><span class="spnError">*</span>
</td>
<td id="tdDocumentCategory">
#Html.DropDownList("ddlDocumentCategory", null, new { #id = "",
#onchange = "AddCategory();", #class =
"required form-control", #name= "DocType" })
</td>
</tr>
<tr>
<td class="tdEditDoc">
<span>Date:</span><span class="spnError">*</span>
</td>
<td>
<input type="text" id="txtPatientDocumentDate" class="Date
required IsDate form-control" name="DocDate" />
</td>
</tr>
<tr>
<td class="tdEditDoc" style="height: 25px;">
<span>Confidental:</span>
</td>
<td>
<input type="checkbox" id="chkPatientDocumentIsConfedential"
/>
</td>
</tr>
<tr>
<td class="tdEditDoc" style="vertical-align: top">
Comments:
</td>
<td>
<textarea id="txtPatientDocumentComments" name="comments"
style="margin-right: 15px; width: 245px; height: 69px;
border-width: 1px; border-color: #c4c4c4;resize:none"
class="form-control">
</textarea>
</td>
</tr>
</table>
<input type="file" name="file" id="file" title="Upload file(s)" />
}
I'm submitting this form to this controller
public void uploadimage(string DocName, string DocType, string DocDate, string d, string comments, HttpPostedFileBase file)
{
}
I'm getting all other parameters except DropDown value.Plus How can I get Value of checkbox(Checked or not). I'm not using any model and want to do without it.
First parameter is the name of field
#Html.DropDownList("DocType", null, new { #id = "", #onchange = "AddCategory();", #class = "required form-control" })
Dropdown bind with null value ?
#Html.DropDownList("ddlDocumentCategory", null, new { #id = "", #onchange = "AddCategory();", #class = "required form-control", #name= "DocType" })
Also make sure name of input fields same as string parameter.
Helpful link
How to submit your form in asp.net mvc

Resources