Upload file to chosen folder - asp.net-mvc-4

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

Related

drop down display empty rows although i get data filled on RefreshDropDownList function?

I work on blazor on .net core 7 . i face issue when display drop down server type
issue is drop down server type display empty although I get data on function RefreshDropDownList(); .
I work on blazor page server names data and inside this page there are drop down servertype
so server type drop down exist on another page ServersNames
server type drop down display empty although function RefreshDropDownList() return 4 items data .
so what is issue and How to solve it ? .
controller action fill drop down is
[HttpGet]
public IActionResult GetAll()
{
return Ok(_IserverTypeService.GetAll());
}
I test action GetAll on controller service type and it return data without any issue
on blazor ui :
<h1>Server Name</h1>
<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal" #onclick="AddClick">
Add ServerNames
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">
#ModalTitle
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</h5>
</div>
<div class="modal-body">
<div class="d-flex flex-row bd-highlight mb-3">
<div class="p-2 w-100 bd-highlight">
<div class="form-group row">
<label for="example-text-input" class="col-3 col-form-label">Server Type</label>
<div class="col-9">
#* <input type="text" class="form-control" #bind="server_Type" />*#
<select class="form-select" #bind="server_Type">
#foreach (var servertype in ServerType)
{
<option value="#servertype.serverTypeId">
#servertype.serverType
</option>
}
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#code
{
public class ServerNamesClass
{
public string server_Type { get; set; }
}
public class ServerTypesClass
{
public int serverTypeId { get; set; }
public string serverType { get; set; }
}
private IEnumerable<ServerTypesClass> ServerType = Array.Empty<ServerTypesClass>();
protected override async Task OnInitializedAsync()
{
await RefreshDropDownList();
}
private async Task RefreshDropDownList()
{
var request = new HttpRequestMessage(HttpMethod.Get, config["API_URL"] + "ServerTypes");
var client = ClientFactory.CreateClient();
var response = await client.SendAsync(request);
using var responsestream = await response.Content.ReadAsStreamAsync();
ServerType = await JsonSerializer.DeserializeAsync<IEnumerable<ServerTypesClass>>(responsestream);
ServerType = Array.Empty<ServerTypesClass>();
}
private async void AddClick()
{
await RefreshDropDownList();
}
In your RefreshDropDownList() you overwrite your ServerType IEnumerable with an empty list: ServerType = Array.Empty<ServerTypesClass>();. This means that your deserialized data will always be overwritten with an empty list.

In my creation process I want to write to another entity than only the used

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;
//...

Asp.net Core Upload File Does not Fire OnPost Code

First thing first i want to apology if this topic has been mentioned before, but i looked for 2 days and never find about my problem.
So, I have a IFormFile script, which is does not throw any error (at least a syntax error) but when i am in the Upload Page, i complete my fields (Name,Description and File) and press Upload button, my OnPost code does not Fire at all and my page just referesh.
This is my Razor Page CREATE.CSHTML
#page
#model Appuntamenti.Models.ViewModel.DocumentCreateViewModel
#{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<div>
<h4>Upload Single file</h4>
</div>
<form method="post" enctype="multipart/form-data" runat="server" asp-action="OnPost" class="mt-3">
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="Name..." />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Description" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Description" class="form-control" placeholder="Description..." />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Document" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="Document" class="form-control custom-file-input" />
<label class="custom-file-label">Choose File..</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success form-control"></button>
#section Scripts {
<script>
$(document).ready(function ()
{
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
</form>
And This is my CREATE.CSHTML.CS page
namespace Appuntamenti.Pages.Documents
{
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _db;
private readonly IHostingEnvironment _hostingEnvironment;
public CreateModel(ApplicationDbContext db, IHostingEnvironment hostingEnvironment)
{
_db = db;
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task<IActionResult> OnPostAsync (DocumentCreateViewModel model)
{
if (!ModelState.IsValid)
{
return NotFound();
}
string uniqueFileName = null;
if(model.Document != null)
{
string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "Documents");
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Document.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
await model.Document.CopyToAsync(new FileStream(filePath, FileMode.Create));
}
DocumentModel newDocument = new DocumentModel
{
Id = model.Id,
Name = model.Name,
Description = model.Description,
DocumentPath = uniqueFileName
};
_db.Add(newDocument);
_db.SaveChanges();
return RedirectToPage("./Index");
}
}
}
And Those are my 2 Models for the IFormFile
public class DocumentModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string DocumentPath { get; set; }
}
public class DocumentCreateViewModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public IFormFile Document { get; set; }
}
BAsically i tried to put a Breakpoint on the Post Method but it does not fire at all,
I tried to run the Website and inspect the elements,header and network and everything is ok.
After some browsing i read that the Onpost method with the IFormFile rely on the TokenValidation, i tried to ignore the validation and see if something change but nothing. I really dont know what i am doing wrong.
I hope i made my point and problem clear and please if you need more info just let me know
You mixed up Asp.Net Core MVC and Razor Page.
Follow steps below:
CreateModel
public class CreateModel : PageModel
{
[BindProperty]
public DocumentCreateViewModel DocumentCreateViewModel { get; set; }
//[HttpPost]
public async Task<IActionResult> OnPostAsync()
{
return RedirectToPage("./Index");
}
View
#page
#model CreateModel
#{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<div>
<h4>Upload Single file</h4>
</div>
<form method="post" enctype="multipart/form-data">
<div class="form-group row">
<label asp-for="DocumentCreateViewModel.Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="DocumentCreateViewModel.Name" class="form-control" placeholder="Name..." />
<span asp-validation-for="DocumentCreateViewModel.Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="DocumentCreateViewModel.Description" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="DocumentCreateViewModel.Description" class="form-control" placeholder="Description..." />
<span asp-validation-for="DocumentCreateViewModel.Description" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="DocumentCreateViewModel.Document" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="DocumentCreateViewModel.Document" type="file" class="form-control custom-file-input" />
<label class="custom-file-label">Choose File..</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success form-control"></button>
#*<input type="submit" value="Submit" />*#
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(document).ready(function () {
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
For more information about Razor page, refer Introduction to Razor Pages in ASP.NET Core

Entity Framework inserting long value instead of actual string value to database for my ASP.NET core site

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

Get value in Create Action

My model.
public class CustomUserTeam
{
public bool IsCation { get; set; }
public int SelectedPlayer { get; set; }
public IEnumerable<SelectListItem> Player { get; set; }
}
My Create View
#model List<superselector.Models.CustomUserTeam>
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "UserPlayers", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Team</h4>
<hr />
#Html.ValidationSummary(true)
<table>
<tr>
<th>
Player
</th>
<th>
Caption
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => item.SelectedPlayer, item.Player)
#Html.ValidationMessageFor(model => item.SelectedPlayer)
</div>
</div>
</td>
<td>
<div class="form-group">
<div class="col-md-10">
#Html.RadioButtonFor(model => item.IsCation, true)
#Html.ValidationMessageFor(model => item.IsCation)
</div>
</div>
</td>
</tr>
}
</table>
<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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My Create Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(List<CustomUserTeam> utvm)// I get null here
{
if (ModelState.IsValid)
{
//db.tblUserTeams.Add(tbluserteam);
//db.SaveChanges();
return RedirectToAction("Index");
}
return View(utvm);
}
public ActionResult Create()
{
//UserTeamViewModel utvm = new UserTeamViewModel();
List<CustomUserTeam> UserTeam = new List<CustomUserTeam>();
List<tblPlayer> batsmen = db.tblPlayers.Where(x => x.tblPlayerSpeciality.Id == 1 || x.tblPlayerSpeciality.Id == 3).OrderBy(x => x.PlayerName).ToList();
List<tblPlayer> Bowlers = db.tblPlayers.Where(x => x.Speciality == 2 || x.Speciality == 3).OrderBy(x => x.PlayerName).ToList();
List<tblPlayer> wk = db.tblPlayers.Where(x => x.Speciality == 4).OrderBy(x => x.PlayerName).ToList();
for (int i = 0; i < 6; i++)
{
UserTeam.Add(new CustomUserTeam() { Player = new SelectList(batsmen, "playerId", "PlayerName") });
}
UserTeam.Add(new CustomUserTeam() { Player = new SelectList(wk, "playerId", "PlayerName") });
for (int i = 0; i < 4; i++)
{
UserTeam.Add(new CustomUserTeam() { Player = new SelectList(Bowlers, "playerId", "PlayerName") });
}
return View(UserTeam);
}
The problem is when i click on "Create" on View, I get null in the Create Action's argument
I dont know whats wrong