Get value in Create Action - asp.net-mvc-4

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

Related

Model binding with multiple rows in ASP.NET Core MVC

I've been stuck on this for so long, any help or direction is appreciated.
Basically I want my controller to pass a json data like this:
Initially, I wanted to do it with model binding, but at this moment even jQuery will be fine.
Model class:
public class Orders
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string ItemName { get; set; }
public double Price { get; set; }
public IEnumerable<SelectListItem> CustomersList { get; set; }
}
Controller code:
// GET: OrdersController/Create
public ActionResult Create()
{
var listCustomers = dbContext.Customers
.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.DepName
});
var orders = new Orders()
{
CustomersList = listCustomers
};
//var orders = new List<Orders>();
return View(orders);
}
// POST: OrdersController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(List<Orders> ordersList)
{
Orders newOrders = new Orders();
foreach (var order in ordersList)
{
newOrders.Id = 0;
newOrders.CustomerId = order.CustomerId;
newOrders.ItemName = order.ItemName;
newOrders.Price = order.Price;
}
// I will be processing newOrders into application/json and sending to the backend API
}
View markup:
#model List<NameSpace.Web.Models.Orders>
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-8">
<div class="form-group">
#Html.LabelFor(model => model.CustomerId, htmlAttributes: new { #class = "control-label col-md-6" })
#Html.DropDownListFor(model => model.CustomerId, Model.CustomersList, "Select Customer ", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DepId, "", new { #class = "text-danger" })
</div>
</div>
<hr>
<div class="col-md-12">
<div class=''></div>
<thead>
<tr>
//<th style="width:150px">Cust. Id</th>
<th style="width:150px">Item Name</th>
<th style="width:150px">Price</th>
</tr>
</thead>
<tbody id="tblOrdersBody">
<tr>
//<td><input name='Orders[0].CustomerId' class="form-control" /></td>
<td><input name='Orders[0].ItemName' class="form-control" /></td>
<td><input name='Orders[0].Price' class="form-control" /></td>
</tr>
</tbody>
<tfooter>
<tr><a hre="#" class="btn btn-success" id="addOrder"></a> </tr>
</tfooter>
</table>
<div class="row">
<div class="tile-footer d-flex justify-content-around">
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn btn-danger" })
<input id="btnSave" type="submit" value="Save Order" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
#section Scripts {
<script>
var i = 1;
$(document).on("click", "#addOrder", function () {
$("#tblOrdersBody").append("<tr>"
//+ "<td><input name='Orders[" + i + "].CustomerId' class='form-control' /></td>"
+ "<td><input name='Orders[" + i + "].ItemName' class='form-control'/></td>"
+ "<td><input name='Orders[" + i + "].Price' class='form-control'/></td>"
+ "<td><button type='button' class='btn btn-danger' id='btnRemove' </buuton></td>"
+ "</tr > ");
i++;
});
</script>
}
I have seen many similar questions , the closest one being this one, but I could figure it out, the controller receives 0 in item counts
public ActionResult Create(List ordersList)
You action parameter named ordersList, please try to modify the name attribute of your input(s) on view page, like below.
<tbody id="tblOrdersBody">
<tr>
<td><input name='ordersList[0].CustomerId' class="form-control" /></td>
<td><input name='ordersList[0].ItemName' class="form-control" /></td>
<td><input name='ordersList[0].Price' class="form-control" /></td>
</tr>
</tbody>
JS code
<script>
var i = 1;
$(document).on("click", "#addOrder", function () {
$("#tblOrdersBody").append("<tr>"
+ "<td><input name='ordersList[" + i + "].CustomerId' class='form-control' /></td>"
+ "<td><input name='ordersList[" + i + "].ItemName' class='form-control'/></td>"
+ "<td><input name='ordersList[" + i + "].Price' class='form-control'/></td>"
+ "<td><button type='button' class='btn btn-danger' id='btnRemove' </buuton></td>"
+ "</tr > ");
i++;
});
</script>
Test Result

Insert multiple rows to Html table at once

I am working on a Master Detail CRUD operations in an ASP.NET Core MVC project. I am trying to perform the Create operation of both Master and Detail models at once, i want to save an order and its order lines (the number of the order lines is the value of the input quantite):
public class Order
{
[Key]
public int OrderId { get; set; }
[Required]
public DateTime OrderDate { get; set; }
[Required]
public int Quantity { get; set; }
public virtual List<OrderLine> OrderLines { get; set; } = new List<OrderLine>();
}
public class OrderLine
{
[Key]
public int OrderLineId { get; set; }
[Required]
public string Designation{ get; set; }
[Required]
public string Serial{ get; set; }
[Required]
public string State { get; set; }
[ForeignKey("OrderId")]
public int OrderId { get; set; }
public virtual Order Order { get; set; }
}
OrderController:
public IActionResult Create()
{
Order order= new Order();
order.OrderLines.Add(new OrderLine() { OrderLineId = 1 });
return PartialView("_AddOrderPartialView", order);
}
[HttpPost]
public IActionResult Create(Order order)
{
if (order != null)
{
_dbcontext.Order.Add(order);
_dbcontext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
_AddOrderPartialView.cshtml:
#model Order
#{
ViewData["Title"] = "_AddOrderPartialView";
}
<div class="modal fade" role="dialog" tabindex="-1" id="addOrder" aria-labelledby="addOrderLabel" aria-hidden="true">
<div class="modal-dialog role="document">
<div class="modal-content">
<div class="modal-header">
<h3>Order</h3>
</div>
<div class="modal-body">
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
.......
<div class="form-group">
<label asp-for="Quantity" class="control-label">Quantity</label>
<input asp-for="Quantity" class="form-control" id="quantite" />
<span asp-validation-for="Quantity" class="text-danger"></span>
</div>
.......
<h3>Order Lines</h3>
<table class="table table-bordered" id="orderLinesTable">
<thead>
<tr>
<th>Designation</th>
<th>Serial</th>
<th>State</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.OrderLines.Count; i++)
{
<tr>
<td>
#Html.EditorFor(x => x.OrderLines[i].Designation, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.OrderLines[i].Serial, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.OrderLines[i].State, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</tbody>
</table>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="javascript:window.location.reload()">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$("#quantite").on('change', function () {
var RowNumber = document.getElementById('quantite').value;
var table = document.getElementById('orderLinesTable');
var rows = table.getElementsByTagName('tr');
var rowOuterHtml = rows[rows.length - 1].outerHTML;
$("#orderLinesTable tbody").find("tr:not(:first)").remove();
for (var i = 0; i < RowNumber-1; i++) {
var newRow = table.insertRow();
newRow.innerHTML = rowOuterHtml;
}
});
</script>
The problem is that this code saves only the first order line in the database. any help?

Upload file to chosen folder

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

Razor Engine Issue in MVC4

When I declare a text box in view page the below error will appear
The type arguments for method 'System.Web.Mvc.Html.InputExtensions.TextBoxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>,
System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly
even I included
<compilation debug="true" targetFramework="4.0">
<!-- ... -->
</compilation>
this in webconfig file
but the same error shows .
............
my code
#Html.TextBoxFor(x => x.Entity, new { #id = "Entityname" })
//..........
model
public string Entity { set; get; }
//.........
//..............
.cshtml page
#model BOSSNew.Models.NewQuantifierM
#{Layout = "../Shared/_Layout.cshtml";}
<div class="breadCrumbHolder">
#{Html.RenderAction("BreadCrumb", "Base", new { menulist = new string[] { "Quantifier", "New Quantifier" }, CurrentURL = new string[] { "#", "#" } });}
</div>
<div class="divContentPane">
<div class="contentPaneHead">
<span class="contentPaneTitle">Users Details </span>
</div>
<table class="ClsTable ClsPad0">
<tr class="even">
<th>#LabelHelper.GetLabel("THLentity", 3)
</th>
<td>
#Html.TextBoxFor(x => x.Entity, new { #id = "Entityname" })
<img title="" id="selectentit" style="margin: 5px" onclick="getentity('txtentity','optentity')"
alt="" src="../../../Name.Controls/Themes/Name-Theme/images/entity.png">
</td>
</tr>
</table>
</div>
//.............
Any idea ?
Any help will be appreciated
You haven't defined model for a view, so you can't use
x => x.Field
expression.
It should look more or less like that:
SomeView.cshtml
#model SomeModel
#{Layout = "../Shared/_Layout.cshtml";}
<div class="breadCrumbHolder">
#{Html.RenderAction("BreadCrumb", "Base", new { menulist = new string[] { "Quantifier", "New Quantifier" }, CurrentURL = new string[] { "#", "#" } });}
</div>
<div class="divContentPane">
<div class="contentPaneHead">
<span class="contentPaneTitle">Users Details </span>
</div>
<table class="ClsTable ClsPad0">
<tr class="even">
<th>#LabelHelper.GetLabel("THLentity", 3)
</th>
<td>
#Html.TextBoxFor(x => x.Entity, new { #id = "Entityname" })
<img title="" id="selectentit" style="margin: 5px" onclick="getentity('txtentity','optentity')"
alt="" src="../../../Name.Controls/Themes/Name-Theme/images/entity.png">
</td>
</tr>
</table>
</div>
SomeModel.cs
public class SomeModel
{
public string Entity { set; get; }
}
And finally in your action method...
public ActionResult SomeMethod()
{
var model = new SomeModel();
//here fill the entity field
return View(model);
}

Multi selectable enum

I am working on a tool so i can keep things organized in a game.
This is my class:
//The item
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Value { get; set; }
public ItemLabel Label { get; set; }
public ItemType Type { get; set; }
public ItemTradeType TradeType { get; set; }
public Trade Trade { get; set; }
}
The Label / Type / TradeType / Trade are enums.
View:
#model EveMonitorV2.Models.Item
#{
ViewBag.Title = "AddItem";
}
<h2>AddItem</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Item</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Value)
</div>
//What should be done here?
<div class="editor-field">
#Html.EditorFor(model => model.Value)
#Html.ValidationMessageFor(model => model.Value)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Trade)
</div>
<div class="editor-field">
#Html.CheckBoxFor()
#Html.ValidationMessageFor(model => model.Trade)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The enum has a whole list of possibilities and I want to make an Item Create view
The problem i run into:
I want to be able to select more options from the enums. (Like this)
Where the categories are my enums.
Is this possible at all in asp.net mvc 4?
(little note: I am still a student, but it isn't a school project)
Create View\Shared\EditorTemplates\Options.cshtml
#using System.ComponentModel.DataAnnotations
#using System.Reflection
#model Enum
#{
var name = ViewData.TemplateInfo.HtmlFieldPrefix;
var type = Model.GetType();
}
#foreach (Enum e in Enum.GetValues(type))
{
var display = type.GetField(e.ToString()).GetCustomAttribute<DisplayAttribute>();
if (display != null && (display.GetAutoGenerateField() ?? true))
{
<label class="checkbox" title="#display.GetDescription()">
<input type="checkbox" name="#name" value="#e.ToString()" checked="#Model.HasFlag(e)" />
#display.Name
</label>
}
}
your enum may be described as next:
[Flags]
public enum MyOptions
{
[Display(AutoGenerateField = false)]
None = 0,
[Display(Name = "Option 1 name")]
Opt1 = 1 << 1,
[Display(Name = "Option 2 name")]
Opt2 = 1 << 2,
[Display(Name = "Option 3 name")]
Opt3 = 1 << 3,
}
than, using:
<div class="editor-field">
#Html.LabelFor(m => m.Trade)
#Html.EditorFor(m => m.Trade, "Options")
</div>