Asp-action edit not getting the data from razor page - asp.net-mvc

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:

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 ;)

Why is my anchor tag in Thymeleaf is not redirecting to the local file

I am trying to redirect to another local web page using a tag in Thymeleaf and Spring boot but it is
not working. I am redirecting from index.html to addEdit.html which are in the same folder.
Here is my code.
index.html
<div class="container">
<p th:text="${message}"></p>
<a th:href="#{/addEdit.html}" class="btn btn-outline-info">Add Employee</a> //not working
<table class="table table-bordered table-dark">
<thead class="">
<tr>
<th>#</th>
<th>Name</th>
<th>Departmen</th>
<th>Position</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="employee : ${employees}" >
<th th:text="${employee.id}"></th>
<td th:text="${employee.name}"></td>
<td th:text="${employee.department}"></td>
<td th:text="${employee.position}"></td>
<td>
<form action="delete">
<input type="submit" value="Delete" class="btn btn-outline-warning"/>
</form>
</td>
<td>
<form action="edit">
<input type="submit" value="Edit" class="btn btn-outline-info"/>
</form>
</td>
</tr>
</tbody>
</table>
</div>
my EmployeeController
#Autowired
private employeeRepo repo;
#RequestMapping("/")
public String home(Model model) {
List<Employee> list = new ArrayList<>();
list = repo.findAll();
model.addAttribute("employees",list);
return "index";
}
#PostMapping("/addEmployee")
public void addEmployee(Employee employee,Model model) {
repo.save(employee);
model.addAttribute("message","Add Successfully");
home(model);
}
my addEdit.html
<div class="container bg-light">
<form action="addEmployee">
<input class="form-control form-control-sm" type="text" placeholder="Name" name="name"><br>
<input class="form-control form-control-sm" type="text" placeholder="Department" name="department"><br>
<input class="form-control form-control-sm" type="text" placeholder="Position" name="postion"><br/>
<input type="submit" value="Add Employee" class="btn btn-outline-success btn-lg btn-block">
</form>
</div>
You should not include the .html in your link. The link should point to a URL that your controller exposes. There is currently no controller method that exposes the /addEdit url for example.
So update your controller:
#GetMapping
public String addEmployee(Model model) {
// add model attributes here as needed first
return "addEdit" // This refers to the view, so 'addEdit.html'
}
Now update the link to:
<a th:href="#{/addEdit}" class="btn btn-outline-info">Add Employee</a>

How to save image in database and display it into Views in MVC 5?

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>

HttpPostedFileBase is coming null

below is the code in my View
#using ClaimBuildMVC.Models
#model IEnumerable<Asset>
#{
ViewBag.Title = "AssetsPage";
Layout = "~/Views/Shared/_SuperAdminLayout.cshtml";
}
<script type="text/javascript">
</script>
#using (Html.BeginForm("AssetsPage", "SuperAdmin", FormMethod.Post,new{enctype = "multipart/form-data"}))
{
<div class="Content-inner-pages">
<div class="TopHeading TopHeading2">
<h2>Assets</h2>
<a class="CreateBtn AssetsBtn" href="Javascript:void(0);" onclick="javascript:$('#hdnIsNew').val('1')">Add Asset</a>
<div class="clearfix"></div>
</div>
<input type="hidden" id="hdnIsNew" value="1" />
<input type="hidden" id="hdnRecId" />
<!-- Slide Popup panel -->
<div class="cd-panel from-right AddAssetForm">
<header class="cd-panel-header">
<h3>Add Asset</h3>
Close
</header>
<div class="cd-panel-container">
<div class="cd-panel-content">
<div class="form-horizontal form-details popup-box">
<div class="form-group">
<label class="col-md-5 control-label">
Asset Title
</label>
<div class="col-md-7">
<input type="text" id="txtTitle" name="txtTitle" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Description</label>
<div class="col-md-7">
<textarea id="txtDesc" class="form-control" cols="5" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Attachment</label>
<div class="col-md-7">
<input type="file" id="file" class="custom-file-input">
</div>
</div>
<div class="form-group">
<div class="col-md-7 col-md-offset-5">
<input type="submit" value="Save" name="actionType" class="btn-class btn-success">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="box">
<div class="box-content Custom-DataTable">
<table id="AdministationAssets" class="table table-hover dt-responsive CustomDatable AdministationAssetsTable" cellspacing="0" width="100%">
<thead>
<tr>
<th style="width:5%;">Assets</th>
<th style="width:15%;">
#Html.DisplayNameFor(model =>model.Title)
</th>
<th style="width:50%;">
#Html.DisplayNameFor(model =>model.Description)
</th>
<th style="width:8%;">Options</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td></td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem =>item.Description)
</td>
<td>
#Html.ActionLink("Edit", "AddEditRecord", new{ id = item.ID }, new { #class = "ActionEdit AssetEdit", onclick ="javascript:GetEditDetails(" + item.ID + ");" })
#Html.ActionLink("Delete", "AssetDelete", new{ id = item.ID }, new { #class = "ActionDelete", onclick = "return confirm('Are You Sure delete this record?');", })
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
and below is my controller that what i want to call when click on save button but 'img' is coming as null and after searching in google i found that to add #using(Html.BeginForm()) but still it is coming as null
[HttpPost]
public ActionResult AssetsPage(Asset ast, HttpPostedFileBase file)
{
using (GenericUnitOfWork gc = new GenericUnitOfWork())
{
if (HttpContext.Request.Files.Count > 0)
{
ast.ContainerName = "reports";
ast.BlobName = HttpContext.Request.Files[0].FileName;
ast.BlobUrl = BlobUtilities.CreateBlob(ast.ContainerName, ast.BlobName, null, GetStream(HttpContext.Request.Files[0].FileName));
ast.FileName = HttpContext.Request.Files[0].FileName;
}
gc.GetRepoInstance<Asset>().Add(ast);
gc.SaveChanges();
}
return RedirectToAction("AssetsPage");
}
Not able to find the solution. Please help or give some reference if possible.
Asp.Net MVC default model binding works with name attribute, So add name="file" attribute with input type="file" as shown :-
<input type="file" name="file" id="file" class="custom-file-input">

Input submit not included in the form

I would like to ask if why the <input type="submit" value="" is not included in the form when I tried to debug the form using F12.
Here is the code:
<table>
<tr>
#if (ViewBag.wthOutSupp == false)
{
using (#Html.BeginForm("Item_SendForApprovalMail", "BuyersTask", FormMethod.Post))
{
<td style="border-color:#1e7c97; background-color:#1e7c97" colspan="5">
#Html.Hidden("id",(int)#ViewBag.prfNo)
<center> <input type ="submit" id="subbttn1" value="Submit the Item/s to Reveiwer" /><center>
</td>
}
}
else if (ViewBag.wthOutSupp == true) {
using (#Html.BeginForm("OnHoldItems", "SearchItems", FormMethod.Post))
{
<td style="border-color:#1e7c97; background-color:#1e7c97" colspan="5">
#Html.Hidden("id",(int)#ViewBag.prfNo)
<center> <input type ="submit" id="subbttn" value="Hold Some Items that Have no Supplier Yet" /><center>
</td>
}
}
</tr>
</table>
In the F12 results:
Could someone help me with this one?
You code is generating invalid html. A <form> element cannot be a child of a <tr> element.
Change your code to
<table>
<tr>
<td style="border-color:#1e7c97; background-color:#1e7c97" colspan="5">
#if (ViewBag.wthOutSupp == false)
{
using (#Html.BeginForm("Item_SendForApprovalMail", "BuyersTask", FormMethod.Post))
{
#Html.Hidden("id",(int)#ViewBag.prfNo)
<center> <input type ="submit" id="subbttn1" value="Submit the Item/s to Reveiwer" /><center>
}
}
else
{
....
}
</td>

Resources