I'm trying to post checkbox information back to the controller so I can save update the data in the database. Currently, I have all the values on the page, but when I check or uncheck the box it never goes to the controller.
Controller
[HttpPost]
public void SaveSettings(SettingsListModel SettingsModel)
{
DataLayer dl = new DataLayer();
}
View
#model WebApplication1.Models.SettingsListModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="#Url.Content("~/Scripts/app.js")"></script>
<title>Settings</title>
</head>
<body>
<h1>Settings</h1>
<div>
<form asp-action="SaveSettings" asp-controller="Home" method="post">
<div align="center">
<div align="center">
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
#Html.HiddenFor(m => m.listOfSettings.ElementAt(i).settingID)
#Html.HiddenFor(m => m.listOfSettings.ElementAt(i).settingText)
<div>
#Html.DisplayTextFor(m => m.listOfSettings.ElementAt(i).settingText)
</div>
<div>
//#Html.HiddenFor(m => m.listOfSettings.ElementAt(i).settingsSelected)
#Html.CheckBoxFor(m => m.listOfSettings.ElementAt(i).settingsSelected)
</div>
<br />
<br />
<br />
}
</div>
</div>
</form>
</div>
</body>
</html>
Model
public class SettingsListModel
{
public List<SettingsModel> listOfSettings { get; set; }
}
public class SettingsModel
{
public int settingID { get; set; }
public string settingText { get; set; }
public bool settingsSelected { get; set; }
}
You cannot use .ElementAt() in your expressions - it is generating name attributes that have no relationship to your model. Since the property is List<T>, then just use the collection indexer
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
#Html.HiddenFor(m => m.listOfSettings[i].settingID)
#Html.HiddenFor(m => m.listOfSettings[i].settingText)
<div>
#Html.DisplayTextFor(m => m.listOfSettings[i].settingText)
</div>
<div>
#Html.CheckBoxFor(m => m.listOfSettings[i].settingsSelected)
</div>
}
Your <form> element is also missing a submit button to post the values to the controller.
Enumerable.ElementAt() returns a type (its return type is TSource), not the property name which must be added in name attribute. Use the collection property indexer instead:
<form asp-action="SaveSettings" asp-controller="Home" method="post">
<div align="center">
<div align="center">
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
#Html.HiddenFor(m => m.listOfSettings[i].settingID)
#Html.HiddenFor(m => m.listOfSettings[i].settingText)
<div>
#Html.DisplayTextFor(m => m.listOfSettings[i].settingText)
</div>
<div>
#Html.CheckBoxFor(m => m.listOfSettings[i].settingsSelected)
</div>
<br />
<br />
<br />
}
</div>
</div>
<!-- add a button here to submit the form -->
<button type="submit">Submit</button>
</form>
Tag helper version:
<form asp-action="SaveSettings" asp-controller="Home" method="post">
<div align="center">
<div align="center">
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
<input asp-for="listOfSettings[i].settingID" type="hidden" />
<input asp-for="listOfSettings[i].settingText" type="hidden" />
<div>
#Html.DisplayTextFor(m => m.listOfSettings[i].settingText)
</div>
<div>
<input asp-for="listOfSettings[i].settingsSelected" type="checkbox" />
</div>
<br />
<br />
<br />
}
</div>
</div>
<!-- add a button here to submit the form -->
<button type="submit">Submit</button>
</form>
Also you need to replace return type from void to ActionResult (or IActionResult if .NET Core is used):
[HttpPost]
public ActionResult SaveSettings(SettingsListModel SettingsModel)
{
DataLayer dl = new DataLayer();
// do something
return View(model);
}
Related
I am building a Book List application. It has the following models:
Book (int Id, string Title, string Type, int MinimumAge) [Id=Key, Title=Required, Type=Required, MinimumAge=Required]
Genre (int Id, string Name) [Master table]
BookGenre (int BookId, int GenreId) [Keyless Entity]
CreateViewModel (Book Book, IEnumerable Genres)
Right now I am working on the CREATE operation.
CONTROLLER code (BookController.cs)
The Create() POST methods of this Controller is incomplete.
using BookList.Data;
using BookList.Models;
using Microsoft.AspNetCore.Mvc;
namespace BookList.Controllers
{
public class BookController : Controller
{
private readonly ApplicationDbContext db;
public BookController(ApplicationDbContext db)
{
this.db = db;
}
// READ (Get)
public IActionResult Index()
{
IEnumerable<Book> bookList = db.Books;
return View(bookList);
}
// CREATE (Get)
public IActionResult Create()
{
// Create custom view model
CreateViewModel model = new CreateViewModel();
model.Book = new Book();
model.Genre = new Genre();
return View(model);
}
// CREATE (Post)
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateViewModel obj)
{
// Write your code here
return RedirectToAction("Index");
}
}
}
VIEW Code (Create.cshtml):
#model CreateViewModel
<div class="row">
<div class="border mt-4">
<div class="row py-2">
<h2 class="text-primary">Add a New Book</h2>
<hr />
</div>
<form asp-action="Create">
<div asp-validation-summary="All" class="text-danger"></div>
#* Title *#
<div class="form-group mb-2">
<label asp-for="Book.Title"></label><br />
<input asp-for="Book.Title" class="form-control" />
<span asp-validation-for="Book.Title" class="text-danger"></span>
</div>
#* Genre *#
<div class="form-group mb-2">
<label>Genre</label><br/>
<div>
#foreach(var genre in Model.Genres)
{
<label for=#genre.Id>#genre.Name</label>
<input type="checkbox" id=#genre.Id value=#genre.Name />
}
</div>
</div>
#* Type(Fiction/Non-Fiction) *#
<div class="form-group mb-2">
<label asp-for="Book.Type"></label><br />
<div>
Fiction <input type="radio" asp-for="Book.Type" value="Fiction" />
Non-Fiction <input type="radio" asp-for="Book.Type" value="Non-Fiction"/>
</div>
<span asp-validation-for="Book.Type" class="text-danger"></span>
</div>
#* Minimum Age(dropdown) *#
<div class="form-group mb-2">
<label asp-for="Book.MinimumAge" class="control-label"></label>
<select asp-for="Book.MinimumAge" class="form-control">
<option value=8>8</option>
<option value=12>12</option>
<option value=16>16</option>
<option value=18>18</option>
</select>
<span asp-validation-for="Book.MinimumAge" class="text-danger"></span>
</div>
<div class="form-group mb-2">
<input type="submit" value="Add" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#*Cient-side validation scripts*#
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Let's say the user enters the following details and clicks Create:
Title="XYZ", Genres="Action,Adventure", Type="Fiction", Minimum Age=12
Then, I want (auto-id, "XYZ","Fiction",12) to go into the Book table. And, (auto-id,1) and (auto-id,2) to go into the BookGenre table.
For your reference, the Genre master table contains the following details. And BookGenre table is a Keyless entity.
You need firstly know that model binding system bind data by name attribute.
From the view design I can see your CreateViewModel contains IEnumerable<Genre> Genres, so the frontend should add name like:Genres[index].PropertyName. But then you will find a problem that if you want to choose discontinuous checkbox, you will receive only continuous value and miss the discontinuous ones.
So suggest you also create a property List<string> GenresList and add name="GenresList" in your frontend.
Here is a whole working demo:
Model:
public class Book
{
public int Id { get; set; }
public int MininumAge { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public ICollection<Genre>? Genres { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Book>? Books { get; set; }
}
public class CreateViewModel
{
public Book Book { get; set; }
public List<Genre>? Genres { get; set; }
public List<string> GenresList { get; set; }
}
View:
#model CreateViewModel
<div class="row">
<div class="border mt-4">
<div class="row py-2">
<h2 class="text-primary">Add a New Book</h2>
<hr />
</div>
<form asp-action="Create">
<div asp-validation-summary="All" class="text-danger"></div>
#* Title *#
<div class="form-group mb-2">
<label asp-for="Book.Title"></label><br />
<input asp-for="Book.Title" class="form-control" />
<span asp-validation-for="Book.Title" class="text-danger"></span>
</div>
#* Genre *#
<div class="form-group mb-2">
<label>Genre</label><br/>
<div>
#foreach(var genre in Model.Genres)
{
<label for=#genre.Id>#genre.Name</label> #* add name here*#
<input type="checkbox" id=#genre.Id value=#genre.Name name="GenresList"/>
}
</div>
</div>
#* Type(Fiction/Non-Fiction) *#
<div class="form-group mb-2">
<label asp-for="Book.Type"></label><br />
<div>
Fiction <input type="radio" asp-for="Book.Type" value="Fiction" />
Non-Fiction <input type="radio" asp-for="Book.Type" value="Non-Fiction"/>
</div>
<span asp-validation-for="Book.Type" class="text-danger"></span>
</div>
#* Minimum Age(dropdown) *#
<div class="form-group mb-2">
<label asp-for="Book.MininumAge" class="control-label"></label>
<select asp-for="Book.MininumAge" class="form-control">
<option value=8>8</option>
<option value=12>12</option>
<option value=16>16</option>
<option value=18>18</option>
</select>
<span asp-validation-for="Book.MininumAge" class="text-danger"></span>
</div>
<div class="form-group mb-2">
<input type="submit" value="Add" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Controller:
public class BooksController : Controller
{
private readonly MvcProj6_0Context _context;
public BooksController(MvcProj6_0Context context)
{
_context = context;
}
// GET: Books/Create
public IActionResult Create()
{
CreateViewModel model = new CreateViewModel();
model.Book = new Book();
model.Genres = _context.Genre.ToList();
return View(model);
}
// POST: Books/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateViewModel obj)
{
if (ModelState.IsValid)
{
var genres = new List<Genre>();
foreach (var item in obj.GenresList)
{
genres.Add(_context.Genre.Where(a => a.Name == item).First());
}
obj.Book.Genres = genres;
_context.Add(obj.Book);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(obj);
}
}
Note:
In .NET 6, it includes the <Nullable>enable</Nullable> element in the project file which makes the property non-nullable. The non-nullable property must be required, otherwise the ModelState will be invalid. You can use ? or initialize the property in the model design to skip the required validation.
If I submit the page the first save goes without a problem
Than I assigned all values to the other entity which I want to write to create there a new record.
Why do I get an System Null Reference. I have in all fields the values which I want?
[
=== here is my c# Code ===========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WorkCollaboration.Data;
using WorkCollaboration.Models;
namespace WorkCollaboration.Pages.TimeReports
{
public class CreateModel : PageModel
{
private readonly WorkCollaboration.Data.WorkCollaborationContext _context;
public CreateModel(WorkCollaboration.Data.WorkCollaborationContext context)
{
_context = context;
}
public IActionResult OnGet()
{
CusContactDropDownDisp = _context.CusContactDropDown.ToList(); // Added for DropDown
SupContactDropDownDisp = _context.SupContactDropDown.ToList(); // Added for DropDown
return Page();
}
[BindProperty]
public TimeReport TimeReport { get; set; }
public IEnumerable<Models.CusContactDropDown> CusContactDropDownDisp { get; set; }
public IEnumerable<Models.SupContactDropDown> SupContactDropDownDisp { get; set; }
public Models.PointsforSupContact PointsforSupContact { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
TimeReport.TimeReportSupContactPointValue = (TimeReport.TimeReportHours * 10);
_context.TimeReport.Add(TimeReport);
await _context.SaveChangesAsync();
//============================================
// Adding new Point Record to Supplier Contact
//============================================
PointsforSupContact.PointsId = TimeReport.TimeReportId;
PointsforSupContact.PointsSupContactId = TimeReport.TimeReportSupplierTalentContactId;
PointsforSupContact.PointsInternalUserId = 1; // User 1 Christof Oberholzer must be entered in Contacts and User
PointsforSupContact.PointsDate = TimeReport.TimeReportDate;
PointsforSupContact.PointsTotal = TimeReport.TimeReportSupContactPointValue;
PointsforSupContact.PointsText = TimeReport.TimeReportText;
PointsforSupContact.PointsTitle = "TimeReporting Points";
_context.PointsforSupContact.Add(PointsforSupContact);
await _context.SaveChangesAsync();
return RedirectToPage("/TimeReportOverview/Index");
}
}
}
==== My Page ======
#page
#using Microsoft.AspNetCore.Localization
#using Microsoft.AspNetCore.Mvc.Localization
#model WorkCollaboration.Pages.TimeReports.CreateModel
#{
ViewData["Title"] = "Create";
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
}
#inject IViewLocalizer Localizer
<h1>Create</h1>
<h4>TimeReport</h4>
<p>
<a asp-page="/TimeReportOverview/Index">Back to Index</a>
</p>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TimeReport.TimeReportSupContactPointValue" value="0"/>
<div class="form-group">
<label asp-for="TimeReport.TimeReportId" class="control-label"></label>
<input asp-for="TimeReport.TimeReportId" value='#ViewData["RandomId"]' readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportCustomerNeedContactId" class="control-label"></label>
</div>
<select id="CusContactId" asp-for="CusContactDropDownDisp" asp-items="#(new SelectList(Model.CusContactDropDownDisp,"CusContactId","CusFullName"))">
<option value="" selected disabled>--Choose Customer--</option>
</select>
<div class="form-group">
<input asp-for="TimeReport.TimeReportCustomerNeedContactId" readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportCustomerNeedContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportSupplierTalentContactId" class="control-label"></label>
</div>
<select id="SupContactId" asp-for="SupContactDropDownDisp" asp-items="#(new SelectList(Model.SupContactDropDownDisp,"SupContactId","SupFullName"))">
<option value="" selected disabled>--Choose Supplier--</option>
</select>
<div class="form-group">
<input asp-for="TimeReport.TimeReportSupplierTalentContactId" readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportSupplierTalentContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportDate" class="control-label"></label>
<input type="datetime-local" asp-for="TimeReport.TimeReportDate" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportHours" class="control-label"></label>
<input asp-for="TimeReport.TimeReportHours" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportHours" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportText" class="control-label"></label>
<input asp-for="TimeReport.TimeReportText" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportText" class="text-danger"></span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeReport.TimeReportState, htmlAttributes: new { #class = "form-group" })
<div class="form-group">
#Html.DropDownListFor(model => model.TimeReport.TimeReportState, new List<SelectListItem>
{
new SelectListItem {Text = "Gebucht", Value = "Reported", Selected = true },
new SelectListItem {Text = "Kontrolliert", Value = "Controlled" },
new SelectListItem {Text = "Verrechnet / Noch nicht bezahlt", Value = "Invoiced / Not yet payed" },
new SelectListItem {Text = "Verrechnet / Bezahlt", Value = "Invoiced / Payed" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TimeReport.TimeReportState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
Back to List
</div>
</form>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$("#CusContactId").on("change", function () {
$("#TimeReport_TimeReportCustomerNeedContactId").val($("#CusContactId").val());
});
$("#SupContactId").on("change", function () {
$("#TimeReport_TimeReportSupplierTalentContactId").val($("#SupContactId").val());
});
</script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Thank you for your help
First In your view:
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
GetHashCodemethod make the Guid to int,please make sure it matches the type in your model.
Then the right way to add new PointsforSupContact is to create a new PointsforSupContact,so you need to delete the code:
public Models.PointsforSupContact PointsforSupContact { get; set; }
and change you code to:
//...
await _context.SaveChangesAsync();
//add this line
var PointsforSupContact=new PointsforSupContact();
PointsforSupContact.PointsId = TimeReport.TimeReportId;
//...
I created an ASP.NET Core 3.1 project. I have a form in it with several checkbox lists. I can get the values into the properties in POST and they are correctly filled in (e.g. List SelectedItems). However for some custom fields I have to do a validation in OnPost() method and if the conditions are not met or a ModelState is not valid, it return Page(). Normally I would expect that every property that was filled in in the form is still filled in, but the checkboxes are always empty and not a single one is checked. The other data (radio buttons, textboxes, etc.) are still filled in.
I even tried to put the values within the Razor page, but even then neither of the checkboxes was checked.
Here is an example of one of the checkboxes:
In Razor page:
#for (var i = 1; i <= 10; i++){
<input name="AreChecked" type="checkbox" id="#i" value="#i" /> #i<br />
<input type="hidden" value="true" id="#i" name="AreChecked" />}
Behind code:
[BindProperties]
public class TestFormModel : PageModel
{
[BindProperty]
public List<int> AreChecked { get; set; }}
public IActionResult OnPost()
{
//some other form check statements here
//...
if (ModelState.IsValid)
{
//process data code...
}
return Page();
}
Can someone help me with this?
You could use JQuery to achieve as shown :
#page
#model RazorPages3_1.AddimgModelModel
<div class="row">
<div class="col-md-4">
<form enctype="multipart/form-data" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Petimg.PetName" class="control-label"></label>
<input asp-for="Petimg.PetName" class="form-control" />
<span asp-validation-for="Petimg.PetName" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="Uploads" class="form-control" />
</div>
#for (var i = 1; i <= 10; i++)
{
<input name="AreChecked" type="checkbox" id="#i" value="#i" /> #i<br />
<input type="hidden" value="true" id="#i" name=""AreChecked" />
}
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
<script>
var checkedlist = #Html.Raw(Json.Serialize(Model.AreChecked));;
if (checkedlist.length > 0) {
$.each(checkedlist, function (index, value) {
$('input[type=checkbox]').each(function () {
var id = $(this).attr("id");
if (id == value) {
$(this).attr('checked', 'checked');
}
})
});
}
</script>
}
Result
My Entity Framework passes a string like this to the database "1b2ef80d-038a-49d8-973b-fc783a53b6a3" instead of the text i placed into the input field, which was "text". How can i only Insert the exact value into the table?
The Database table i'm currently testing is just one column and is set to VARCHAR(400).
Context class:
modelBuilder.Entity<Contract>(entity =>
{
entity.HasKey(e => e.Contract1)
.HasName("Contract$PrimaryKey");
entity.Property<string>(e => e.Contract1)
.HasColumnName("Contract")
.HasColumnType("VARCHAR(400)")
.IsUnicode(false)
.HasMaxLength(400);
});
Model class:
[Key]
[Column(TypeName = "VARCHAR(400)")]
[StringLength(400)]
public string Contract1 { get; set; }
View page:
<form asp-action="Create">
<div class="form-horizontal">
<h4>Contract</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
#Html.LabelFor(model => model.Contract1, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.EditorFor(model => model.Contract1)
#Html.ValidationMessageFor(model => model.Contract1)
<span class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
</body>
</html>
And Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Contract")] Contract Contract)
{
if (ModelState.IsValid)
{
_context.Add(Contract);
await _context.SaveChangesAsync();
return RedirectToAction("Create");
}
ViewData["Contract"] = new SelectList(_context.Contract, "Contract", "Contract", Contract.Contract1);
return View(Contract);
}
}
}
i had to add the class, instead of just the context.Add i had to make it context.class.Add:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Contract Contract)
{
if (ModelState.IsValid)
{
_context.Contract.Add(Contract);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["Contract"] = new SelectList(_context.Contract, "Contract", "Contract", Contract.Contract1);
return View(Contract);
}
}
}
I have radio buttons with the folder name. A user can choose a folder name where he/she wants to upload a file. then he/she choose the folder name and upload the file
this is the model:
public class UploadViewModel
{
public string Id { get; set; }
[Required]
[Display(Name = "FormToUpload", ResourceType = typeof(Resources.Entity.Form))]
public HttpPostedFileBase UploadData { get; set; }
private UploadModel _uploadModel;
public string[] Directories { get; set; }
public bool? IsActive { get; set; }
public UploadViewModel(UploadModel uploadModel)
{
_uploadModel = uploadModel;
}
}
this the method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadFile([Bind(Include = "UploadData")] LibraryUploadModel libraryUpload, string designId, string[] selectedFile)
{
TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
if (Request != null)
{
//HttpPostedFileBase file = Request.Files["UploadData"];
if ((libraryUpload.UploadData != null) && (libraryUpload.UploadData.ContentLength > 0) && !string.IsNullOrEmpty(libraryUpload.UploadData.FileName))
{
var fileName = Path.GetFileName(libraryUpload.UploadData.FileName);
//var path = Path.Combine(Server.MapPath("~/img/Data"), fileName);
libraryUpload.UploadData.SaveAs(path);
}
}
return View();
}
and this is the view:
#model SenecaFormsServer.Areas.Dashboard.Models.UploadViewModel
ViewBag.Title = Resources.Entity.DesignTemplate.UploadForm;
}
#Html.Partial("~/Areas/_Shared/_BreadCrumbsPartial.cshtml")
<!-- widget grid -->
<section id="widget-grid">
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-xs-12 ">
#Html.RenderNotifications()
</div>
<div class="col-xs-12 padding-bottom-10">
<button type="submit" value="UploadFile" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.Upload</button>
<i class="fa fa-fw fa-times"></i>#Resources.Action.Navigation.Cancel
</div>
</div>
<div class="well no-padding">
<div class="bg-color-white">
<div class="row padding-10">
<div class="col-xs-12">
<h4>#Resources.Entity.DesignTemplate.FileName</h4>
</div>
<div class="col-xs-12 margin-bottom-10 margin-top-10">
<div class="form-horizontal">
#Html.ValidationSummary(true)
#*<div class="form-group">
#Html.LabelFor(model => model.UploadData, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10">
<input name="#Html.NameFor(model => model.UploadData)" type="file" />
#Html.ValidationMessageFor(model => model.UploadData)
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<table>
#foreach (var item in Model.Directories)
{
<tr>
<td>
#Html.RadioButton("Assigned", Model.IsActive.HasValue ? Model.IsActive : false);
#Html.Label(item)
</td>
</tr>
}
</table>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UploadData, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10">
<input name="#Html.NameFor(model => model.UploadData)" type="file" />
#Html.ValidationMessageFor(model => model.UploadData)
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</section>
<!-- end widget grid -->
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Thank you
If i now try to upload I get this error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 746: {
Line 747: TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
Line 748: var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
Line 749:
Line 750: foreach (var item in uploadViewModel)
Source File: b:\Seneca\Producten\FormsServer\Trunk\SenecaFormsServer\Areas\Dashboard\Controllers\DesignTemplateController.cs