ASP.NET MVC & C# DropDownListFor set and get value - c#

Revised a bunch of code for ASP.NET MVC, Everywhere example for 500 lines of code at least.
There is a list of the Plane directory (key.plane key). There is a current InstanceC entry (link to the InstanceC.ID_plane directory)
How easy is it to set the value from the controller of the loaded list and read the selected value by the user?
I have the following code:
AccountController.cs
public ActionResult ClickDetails(String slctplane, String Description,String SaveInstance, string AddInstance, string ActivePlane, string RestartInstance, string GeneratePassword, string ResetDB, String DelInstance)
{
if (ActivePlane != null)
{
String id_plane = slctplane; // Выбранный тарифный план
}
}
Model classes:
public class Plane
{
[Key]
public int key_plane { get; set; }
public String Name_plane { get; set; }
public int Num_users { get; set; }
public int Size_db { get; set; }
public int Freq_in_minute { get; set; }
public int Price_usd { get; set; }
public int Price_r { get; set; }
}
public class InstanceC
{
[Key]
public int key_Instance { get; set; }
public String ID_user { get; set; }
public int ID_Server { get; set; }
public String Login_inst { get; set; }
public String Password_inst { get; set; }
public int SetStatusForBroker { get; set; }
public String Description { get; set; }
public int ID_plane { get; set; }
public String Name_plane { get; set; }
public int Price_usd { get; set; }
public int Price_r { get; set; }
public int Num_users { get; set; }
public int RealStatus { get; set; }
public String Name_server { get; set; }
public String Name_domain { get; set; }
}
I have the following markup in Details.cshtml:
#{
ViewBag.Title = "Подробнее/";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
#using (Html.BeginForm("ClickDetails", "Account", FormMethod.Post))
{
<div>
<h2>Подробнее</h2>
<div class="cloud-box">
<div class="row">
<div class="col-md-12">
<h3>Информация о инстанции</h3>
</div>
</div>
#foreach (var i in ViewBag.Details)
{
<div class="row">
<div class="col-md-8">
<table class="table cloud-data">
<tbody>
<tr>
<td>Название</td>
<td>
<input name="Description" type="text" value="#i.Description" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">
<button name="SaveInstance" value="#i.key_Instance" type="submit" class="btn btn-success btn-sm pull-right">
<i class="glyphicon glyphicon-floppy-saved"></i>
Сохранить
</button>
<button name="DelInstance" value="#i.key_Instance" type="submit" class="btn btn-danger btn-sm pull-right">
<i class="glyphicon glyphicon-floppy-saved"></i>
Удалить
</button>
</td>
</tr>
<tr>
<td>Тарифный план</td>
<td>
<button type="button" value="" class="btn btn-success btn-sm pull-right" data-toggle="modal" data-target="#ActivePlaneDlg">
<i class="glyphicon glyphicon-usd"></i>
Активировать
</button>
<div class="modal fade" id="ActivePlaneDlg" tabindex="-1" role="dialog" aria-labelledby="ActivePlaneTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ActivePlaneTitle">Активация тарифного плана</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Старый тарифный план будет аннулирован.
Активировать и оплатить новый тарифный план?
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="ActivePlane" name="ActivePlane" value="id_plane=1">
<i class="glyphicon glyphicon-usd"></i>
Да
</button>
<!--
<input type="submit" name="ActivePlane" value="Сохранить" />
<button type="button" class="btn btn-secondary" data-dismiss="modal">Да</button> -->
<button type="button" class="btn btn-primary" data-dismiss="modal">Нет</button>
</div>
</div>
</div>
</div>
</tr>
<tr>
<td>Статус тарифного плана</td>
<td>
<font color="green">Активирован</font>
</td>
</tr>
<tr>
<td>Дата продления</td>
<td>01.01.2019</td>
</tr>
<tr>
<td>Автопродление</td>
<td>Активировано</td>
</tr>
<tr>
<td>Сервер</td>
<td>#i.Name_domain</td>
</tr>
<tr>
<td>Пользователь</td>
<td>
#i.Login_inst
<button type="button" class="btn btn-cloud btn-cloud-danger btn-sm pull-right" data-toggle="modal" data-target="#RebootInstanceDlg">
<i class="glyphicon glyphicon-repeat"></i>
Перезапуск
</button>
<div class="modal fade" id="RebootInstanceDlg" tabindex="-1" role="dialog" aria-labelledby="RebootInstanceTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="RebootInstanceTitle">Перезагрузка</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Вы уверены, что хотите перезагрузить инстанс?
</div>
<div class="modal-footer">
<!-- <button type="button" name="RestartInstance" class="btn btn-secondary" data-dismiss="modal">Да</button>
<input type="submit" name="RestartInstance" value="Да" />-->
<button class="btn btn-secondary" id="RestartInstance" name="RestartInstance" value="id_instance=1">
<i class="glyphicon glyphicon-repeat"></i>
Да
</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Нет</button>
</div>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td>
Пароль
</td>
<td>
#i.Password_inst
<button type="button" class="btn btn-cloud btn-cloud-danger btn-sm pull-right" data-toggle="modal" data-target="#ResetPasswordInstanceDlg">
<i class="glyphicon glyphicon-refresh"></i>
Сгенерировать
</button>
<div class="modal fade" id="ResetPasswordInstanceDlg" tabindex="-1" role="dialog" aria-labelledby="ResetPasswordInstanceTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ResetPasswordInstanceTitle">Генерация нового пароля</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Сгенерировать новый пароль?
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="GeneratePassword" name="GeneratePassword" value="id_plane=2">
<i class="glyphicon glyphicon-refresh"></i>
Да
</button>
<!-- <button type="button" id="GeneratePassword" class="btn btn-secondary" value="id_psw=1" name="GeneratePassword" data-dismiss="modal">Да</button> -->
<!--<input type="submit" name="GeneratePassword" value="Да" />-->
<!--
<button class="btn btn-danger" id="resetdb" name="ResetDB" value="id_plane=1">
<i class="glyphicon glyphicon-trash"></i>
Сброс БД
</button>
>-->
<button type="button" class="btn btn-primary" data-dismiss="modal">Нет</button>
</div>
</div>
</div>
</div>
</td>
</tr>
<!----------------------------Начало: Список доступных портов---------------------------------------------------->
#foreach (var a in ViewBag.PortsDetail)
{
<tr>
<td>Протокол</td>
<td>
#a.NamePort
</td>
</tr>
<tr>
<td>Порт №</td>
<td>
#a.NumPort
</td>
</tr>
<hr>
}
<!---------------------------Конец: Список доступных портов------------------------------------------------------>
</tbody>
</table>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<h3>Сброс БД</h3>
</div>
<div class="col-md-10">
Это сотрет все сохраненные сообщения в БД.
</div>
<div class="col-md-2">
<form action="https://*/console/9751325/details/reset" class="pull-right" id="reset-form" method="post">
<button class="btn btn-danger" id="resetdb" name="ResetDB" value="id_plane=1">
<i class="glyphicon glyphicon-trash"></i>
Сброс БД
</button>
</form>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<h3>API</h3>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<strong>API ключ</strong>
</div>
<div class="col-sm-10">
<code>0942387c-de7c-4241-2349da3-e59e4c1afdf6</code>
</div>
</div>
}
</div>
</div>
}
</body>
</html>

You can use Model for form. That allow you setup default values in the controller and handle it from form POST.
Your view model
class PlaneFormModel
{
public string slctplane { get; set; }
public string Description { get; set; }
public string SaveInstance { get; set; }
public string AddInstance { get; set; }
public string ActivePlane { get; set; }
public string RestartInstance { get; set; }
public string GeneratePassword { get; set; }
public string ResetDB { get; set; }
public string DelInstance { get; set; }
public string DropDownValueSelected { get; set; }
public string List<SelectListItem> DropDownValues { get; set; }
}
Your HttpGet controller method
[HttpGet]
public ActionResult ClickDetails()
{
// set view model with dropdown values, also you can use linq from your list of values
// also you can set default value for dropdown
var formModel = new PlaneFormModel
{
DropDownValueSelected = "defaultValue", // <---- value
DropDownValues = new List<SelectListItem>
{
new SelectListItem
{
Key = "key",
Value = "val"
}
}
};
return View(formMmodel);
}
Your HttpPost controller method
[HttpPost]
public ActionResult ClickDetails(PlaneFormModel formModel)
{
// bind model from form also you can use FormCollection instead.
if (!string.IsNullOrEmpty(formModel.DropDownValueSelected))
{
...
}
...
}
And in view simply use razor template helper
#Html.DropDownListFor(m => m.DropDownValueSelected,
Model.DropDownValues,
"Select plane")
Source 1
Source 2

Here is how you do it:
public class TheModel
{
//Can be string, int, Guid, etc. Usually this is the index key.
public int SelectedValue {get;set;}
public List<SelectListItem> TheList {get;set;}
public TheModel()
{
TheList = new List<SelectListItem>();
}
}
For instance you have a model with int type index key. You get get it from the database and insert it on the list.
TheModel model = new TheModel();
using(MigrationDB db = new MigrationDB())
{
model.TheList = db.Plane.Select(m => new SelectListItem()
{
Value = m.PlaneId.ToString(), //Value can hold only string
Text = m.PlaneName //this is the <option>text</option>
}.ToList();
}
This is how you write it in Razor view:
#model TheModel
.....
<form> //You can use Html.BeginForm() to create the form tag.
#Html.DropDownListFor(m => m.SelectedValue, //This will bind the selected option into `SelectedValue` property
Model.TheList, //This will fill up your <option> with the value from the list.
" Select Plane ", //If no value is selected this option will be selected with the value null
new { #class = "custom-class", ...} //Html attribute you want to put here.
);
</form>
So if you select an option from the dropdown box, it will be bound to SelectedValue property.
[HttpPost]
public ActionResult PassTheValue(TheModel model) //Pass the entire model
{
var theSelectedValue = model.SelectedValue;
...
}
You should pass the entire model from the Html page view into the controller.
A reference to Html.BeginForm() source

Related

.net 6 Core MVC Paging for a navigation property

I am trying to build an application like in the tutorial in Microsoft: https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-6.0
So i have a model like this:
using ABCrm2.Data.Account;
using ABCrm2.Models.Allgemein;
using ABCrm2.Models.Vertrieb;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.CodeAnalysis;
namespace ABCrm2.Models.Stammdaten
{
public class Land
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[NotNull]
[MaxLength(40)]
public string? Landbezeichnung { get; set; }
[MaxLength(3)]
public string? LandKurz { get; set; }
[Required]
[NotNull]
[MaxLength(10)]
public string? LandVorwahl { get; set; }
public DateTime? ErstellDatumZeit { get; set; }
public DateTime? ÄnderDatumZeit { get; set; } = DateTime.Now;
public bool Aktiv { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public ICollection<Bundesland>? Bundesländer { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
namespace ABCrm2.Models.Stammdaten
{
public class Bundesland
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
[NotNull]
[MaxLength(30)]
public string BundeslandText { get; set; }
[ForeignKey("Länder")]
[Required]
[NotNull]
public int LandId { get; set; }
public Land? Länder { get; set; }
public bool Aktiv { get; set; }
public DateTime? ErstellDatumZeit { get; set; }
public DateTime? ÄnderDatumZeit { get; set; } = DateTime.Now;
[Timestamp]
public byte[] RowVersion { get; set; }
}
}
in the Index of Land i use the helper PaginatedList.cs like in the tutorial:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace ContosoUniversity
{
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage => PageIndex > 1;
public bool HasNextPage => PageIndex < TotalPages;
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
}
in the details of land i would like to have the land and the list of countries (Bundesland)
Controller Part:
public async Task<IActionResult> Details(int? id, int? seiteBL)
{
if (id == null || _context.Länder == null)
{
return NotFound();
}
var land = await _context.Länder
.AsNoTracking()
.Include(a => a.Bundesländer.Where(s => s.Aktiv.Equals(true)))
.FirstOrDefaultAsync(m => m.Id == id);
if (land == null)
{
return NotFound();
}
var pageSizeBL = Configuration.GetValue("PageSize", 16);
double AnzahlTrefferBL = land.Bundesländer.Count();
int? aktuelleSeiteBL = seiteBL;
if (aktuelleSeiteBL == null)
{
aktuelleSeiteBL = 1;
}
ViewData["AnzahlTrefferBL"] = land.Bundesländer.Count();
ViewData["AnzahlSeitenBL"] = (int)Math.Ceiling(AnzahlTrefferBL / pageSizeBL);
ViewData["AktuelleSeiteBL"] = aktuelleSeiteBL;
//how do i get the paging of Bundesländer?
return View(land);
}
the view:
#using ABCrm2.Helper
#using ABCrm2.Models.Stammdaten
#model Land
#{
ViewData["Title"] = "Land anzeigen";
}
<form method="post" asp-action="Details">
<div class="row">
<div class="col-1">
<div class="input-group-sm mb-1">
<h2><input disabled type="text" asp-for="Id" class="form-control trechts" title="die eindeutige Nummer des Landes" /></h2>
</div>
</div>
<div class="col-11">
<h2>Land anzeigen</h2>
</div>
<hr />
</div>
<div class="row">
<div class="col-1">
<a asp-area="" asp-controller="Land" asp-action="Edit" asp-route-id= "#Model.Id" class="btn btn-primary btn-sm" data-toggle="tooltip" data-placement="top" title="Land ändern">
<i class="bi bi-pencil-square"></i>
</a>
<a asp-area="" asp-controller="Land" asp-action="Index" class="btn btn-secondary btn-sm" data-toggle="tooltip" data-placement="top" title="Zurück zur Liste">
<i class="bi bi-list-columns"></i>
</a>
<a asp-area="" asp-controller="Land" asp-action="Details" class="btn btn-refresh btn-sm" data-toggle="tooltip" data-placement="top" title="Aktualisieren">
<i class="bi bi-arrow-clockwise"></i>
</a>
</div>
<div class="col-5">
<div class="row">
<div class="border p-2">
<div class="row">
<div class="col-12">
<div class="input-group-sm mb-1">
<input asp-for="Aktiv" title="Nur aktive Länder können verwendet werden" disabled/>
<label asp-for="Aktiv" class="control-label" ></label>
</div>
</div>
</div>
<div class="row">
<div class="col-2">
<div class="input-group-sm mb-1">
<label asp-for="LandKurz"></label>
<input asp-for="LandKurz" class="form-control" title="Das Länderkürzel" disabled/>
</div>
</div>
<div class="col-10">
<div class="input-group-sm mb-1">
</div>
</div>
</div>
<div class="input-group-sm mb-1">
<label asp-for="Landbezeichnung"></label>
<input asp-for="Landbezeichnung" class="form-control" title="Das Land" disabled />
</div>
<div class="row">
<div class="col-3">
<div class="input-group-sm mb-1">
<label asp-for="LandVorwahl"></label>
<input asp-for="LandVorwahl" class="form-control" title="Die Länder-Telefonvorwahl" disabled />
</div>
</div>
<div class="col-9">
<div class="input-group-sm mb-1">
</div>
</div>
</div>
</div>
</div> #*row*#
<div class="row">
<div class="border p-2">
<div class="row">
<div class="col-4">
#Html.DisplayNameFor(model => model.ErstellDatumZeit)
</div>
<div class="col-4">
#Html.DisplayNameFor(model => model.ÄnderDatumZeit)
</div>
</div>
<div class="row">
<div class="col-4">
#Html.DisplayFor(model => model.ErstellDatumZeit)
</div>
<div class="col-4">
#Html.DisplayFor(model => model.ÄnderDatumZeit)
</div>
</div>
</div>
</div> #*row*#
</div>
<div class="col-lg-4 col-sm-11 col-md-11">
<div class="table-responsive">
<table class="table table-striped table-dark table-sm caption-top">
<caption>
<div class="row">
<div class="col-9">
<h3>Bundesländer</h3>
</div>
<div class="col-3">
</div>
</div>
</caption>
<thead>
<tr>
<th>
<div class="btn-group btn-group-sm" role="group">
<a asp-area="" asp-controller="Bundesländer" asp-action="Create" class="btn btn-success btn-sm" data-toggle="tooltip" data-placement="top" title="Neues Bundesland anlegen">
<i class="bi bi-plus-square"></i>
</a>
<a class="btn btn-info mx-2" data-bs-toggle="offcanvas" data-placement="top" data-toggle="tooltip" data-bs-target="#suche" aria-controls="suche" title="Bundesland suchen">
<i class="bi bi-search"></i>
</a>
<a asp-area="" asp-controller="Bundesländer" asp-action="Index" class="btn btn-refresh btn-sm" data-toggle="tooltip" data-placement="top" title="Aktualisieren">
<i class="bi bi-arrow-clockwise"></i>
</a>
</div>
</th> <!-- wird benötigt für Edit, Delete Buttons -->
<th>
<a asp-action="Index" asp-route-sortierung="#ViewData["AktivSortParm"]" asp-route-currentFilter="#ViewData["CurrentFilter"]" title="nur aktive Bundesländer können gewählt werden">Aktiv</a>
</th>
<th>
<a asp-action="Index" asp-route-sortierung="#ViewData["IdSortParm"]" asp-route-currentFilter="#ViewData["CurrentFilter"]" title="Die eindeutige ID des Bundeslandes">Id</a>
</th>
<th>
<a asp-action="Index" asp-route-sortierung="#ViewData["BundeslandTextSortParm"]" asp-route-currentFilter="#ViewData["CurrentFilter"]" title="Das Bundesland">Bundesland</a>
</th>
<th>
<a asp-action="Index" asp-route-sortierung="#ViewData["DateÄnderungSortParm"]" asp-route-currentFilter="#ViewData["CurrentFilter"]" title="Datum der letzten Änderung">Änderungsdatum</a>
</th>
<th>
<a asp-action="Index" asp-route-sortierung="#ViewData["DateErstellSortParm"]" asp-route-currentFilter="#ViewData["CurrentFilter"]" title="Datum der Ersterfassung">Erstelldatum</a>
</th>
</tr>
</thead>
<tbody>
#if (Model.Bundesländer.Count() > 0)
{
#foreach (var item in Model.Bundesländer)
{
<tr>
<td>
<div class="btn-group btn-group-sm" role="group">
<a asp-controller="Bundesländer" asp-action="Details" asp-route-id="#item.Id" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Bundesland anzeigen">
<i class="bi bi-eye"></i>
</a>
<a asp-controller="Bundesländer" asp-action="Edit" asp-route-id="#item.Id" class="btn btn-primary mx-2" data-toggle="tooltip" data-placement="top" title="Bundesland ändern">
<i class="bi bi-pencil-square"></i>
</a>
<a asp-controller="Bundesländer" asp-action="Delete" asp-route-id="#item.Id" class="btn btn-danger" data-toggle="tooltip" data-placement="top" title="Bundesland löschen">
<i class="bi bi-trash-fill"></i>
</a>
</div>
</td>
<td>#Html.DisplayFor(modelItem => item.Aktiv)</td>
<td>#Html.DisplayFor(modelItem => item.Id)</td>
<td>#Html.DisplayFor(modelItem => item.BundeslandText)</td>
<td>#Html.DisplayFor(modelItem => item.ÄnderDatumZeit)</td>
<td>#Html.DisplayFor(modelItem => item.ErstellDatumZeit)</td>
</tr>
}
}
else
{
<tr>
<td colspan="12" class="text-warning">keine Datensätze vorhanden</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="col-1">
</div>
</div>
</form>
it is all ok - the Bundesländer are listet complete - but how to do paging there for the navigation property by using the helper PaginatedList.cs ??

ASP.NET MVC : insert HTML table into database with other form data

I'm trying to develop an ASP.NET MVC project for product creation. Currently, I have the following code:
Model:
public class ProductModel
{
public string ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductBrandID { get; set; }
public string ProductBrandName { get; set; }
public string ProductCategoryID { get; set; }
public string ProductCategoryName { get; set; }
public string Inventory { get; set; }
public string Photos { get; set; }
public decimal Price { get; set; }
public decimal Discount { get; set; }
public decimal Tax { get; set; }
public List<ProductModel> Products { get; set; }
}
View
(It has a form that contains some fields about the product and a table for the inventory.)
<div class="modal-body" style="padding-left:40px;padding-right:40px">
<br />
#using (Html.BeginForm("CreateProduct", "Admin", FormMethod.Post))
{
<form class="Product">
<div class="form-group row">
<div class="col-sm-7" style="padding-right:20px">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
Product Name: <input type="text" class="form-control" id="txtNewProductname" name="ProductName">
</div>
</div>
<div class="form-group">
Description: <textarea class="form-control" cols="40" rows="2" id="txtNewProductDescription" name="ProductDescription"></textarea>
</div>
<div class="form-group row">
<div class="col-sm-6">
Brand: <select id="selectNewProductBrand" class="form-control" name="ProductBrandID">
<option hidden disabled selected> </option>
#foreach (var item in Model.BrandMenus)
{
<option value="#Html.DisplayFor(module => item.BrandID)">#Html.DisplayFor(module => item.BrandName)</option>
}
</select>
</div>
<div class="col-sm-6 mb-3 mb-sm-0">
Category: <select id="selectNewProductCategory" class="form-control" name="ProductCategoryID">
<option hidden disabled selected> </option>
#foreach (var item in Model.Categories)
{
<option value="#Html.DisplayFor(module => item.CategoryID)">#Html.DisplayFor(module => item.CategoryName)</option>
}
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 mb-3 mb-sm-0">
Price: <input type="text" class="form-control" style="text-align:right;" id="txtNewProductPrice" name="Price">
</div>
<div class="col-sm-4">
Discount: <input type="text" class="form-control" style="text-align:right;" id="txtNewProductDiscount" name="Discount">
</div>
<div class="col-sm-4">
Tax: <input type="text" class="form-control" style="text-align:right;" id="txtNewProductTax" name="Tax">
</div>
</div>
</div>
<div class="form-group col-sm-5" style="border: thin solid lightgray;border-radius: 15px;padding:20px">
Photos:
</div>
</div>
<div class="form-group">
Inventory:<table class="table table-bordered" id="newTableInventory" width="100%" cellspacing="0">
<thead>
<tr>
<th hidden>Inventory ID</th>
<th>Variant</th>
<th>Stock</th>
<th hidden>Location ID</th>
<th>Location</th>
<th>Remarks</th>
<th width="100px">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td hidden>1000001</td>
<td>Blue</td>
<td>3</td>
<td hidden>123</td>
<td>Shop</td>
<td>Ok</td>
<td></td>
</tr>
</tbody>
</table>
<a href="#" data-toggle="modal" data-target="#CreateNewVariantModal" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm">
<i class="fas fa-plus fa-sm text-white-50"></i> Add Variant
</a>
</div>
<div class="modal-footer">
<button type="submit" id="btnNewProduct" class="btn btn-primary">Save</button>
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
</div>
</form>
}
</div>
UI
Controller
public class AdminController : Controller
{
public ActionResult CreateProduct(ProductModel objModel)
{
ProductModelDal cmProducts = new ProductModelDal();
try
{
int result = cmProducts.CreateProduct(objModel);
if (result == 1)
{
ViewBag.Message = "Product has been added successfully";
ModelState.Clear();
}
else
{
ViewBag.Message = "Unsucessfull";
ModelState.Clear();
}
return RedirectToAction("Products");
}
catch
{
throw;
}
}
}
public class ProductModelDal
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.CLDBConString);
public int CreateProduct(ProductModel productModel)
{
SqlCommand cmd = new SqlCommand("sp_Product_Create", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PRODUCTNAME", productModel.ProductName);
cmd.Parameters.AddWithValue("#PRODUCTDESCRIPTION", productModel.ProductDescription);
cmd.Parameters.AddWithValue("#BRANDID", productModel.ProductBrandID);
cmd.Parameters.AddWithValue("#CATEGORYID", productModel.ProductCategoryID);
cmd.Parameters.AddWithValue("#PHOTOS", productModel.Photos);
cmd.Parameters.AddWithValue("#PRICE", productModel.Price);
cmd.Parameters.AddWithValue("#DISCOUNT", productModel.Discount);
cmd.Parameters.AddWithValue("#TAX", productModel.Tax);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
}
The insert of product basic information into database is working fine.
But is there a way to insert the data inside the table at the same time?
I saw this article but I don't know how to integrate it with my current code. Please help me.
Thank you in advance.

Model not posting from View to Controller

I have a view with a model that post data to controller but after submitting, posted model has default values. How can I resolve this issue?
My Model:
public partial class SaleModel
{
[Required]
public byte CategoryId { get; set; }
[Required]
public int UserId { get; set; }
[Required]
[Range(1, int.MaxValue)]
public int ProductId { get; set; }
[Required]
[StringLength(11)]
[RegularExpression("^(989|09|9)[012349][0-9]\\d{7}$")]
public string Mobile { get; set; }
[Required]
[Range(5000, 10000000]
public int Amount { get; set; }
[Required]
public float DiscountPercent { get; set; }
}
I have to submit button in view and string submit in Controller for that:
#using EKhadamat.Models.Sales
#using EKhadamat.Services.Operators
#using EKhadamat.Core.Models.Products
#model SaleModel
#inject IOperatorService operatorService
#{
ViewData["Title"] = "شارژ ارزان";
var category = Category.Charge;
}
#using (Html.BeginForm("Sale", "Topup", FormMethod.Post))
{
<div class="card border border-primary shadow view-height bg-light">
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<h1 class="text-primary">
شارژ ارزان
<label id="lblDescription"></label>
</h1>
<h6 class="text-info mb-3"><span class="fas fa-hand-point-left fa-fw ml-1"></span>با 2 درصد تخفیف، سیم کارت اعتباری خود را شارژ کنید.</h6>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fas fa-mobile-alt fa-fw text-primary"></i>
</span>
</div>
<input asp-for="Mobile" class="form-control" type="number" placeholder="#Html.DisplayFor(model => model.Mobile)" />
<button ID="LNK_Charge_Contacts" class="btn btn-info" title="لیست مخاطبین" CommandArgument="TB_Charge_Mobile">
<span class="fas fa-address-book fa-fw fa-inverse"></span>
</button>
</div>
<div class="mb-2">
<span asp-validation-for="Mobile" class="text-danger text-desc"></span>
</div>
...
<button id="btnSubmit" type="button" class="btn btn-block btn-primary mb-5">بررسی نهایی</button>
<div id="divReceipt" class="d-none">
<div class="row">
<div class="col-12">
<div class="alert alert-success mb-2" role="alert">
<h4>
<span>پیش‌فاکتور</span>
<span class="fas fa-receipt fa-fw float-left"></span>
</h4>
<hr />
<label id="lblTitle"></label>
<br />
<label id="lblOperator"></label>
<br />
<label id="lblMobile"></label>
<br />
<label id="lblCount"></label>
<hr />
<div class="text-center">
<span class="fas fa-2x fa-coins fa-fw ml-1 text-gold"></span>
<label id="lblPayment"></label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6">
<button id="btnCredit" type="submit" name="submit" value="Credit" class="btn btn-block btn-info mb-2" disabled="#Model.UserId <= 0 ? 'disabled' : ''">خرید اعتباری</button>
</div>
<div class="col-lg-6 col-sm-6">
<button id="btnCash" type="submit" name="submit" value="Cash" class="btn btn-block btn-primary mb-2">خرید نقدی</button>
</div>
</div>
<button id="btnReturn" type="button" class="btn btn-block btn-secondary mb-5">بازگشت و ویرایش</button>
</div>
</div>
<div class="col-lg-6">
<div class="card">
<div class="card-body">
<img id="imgCharge" src="~/img/charge.jpg" class="img-fluid" alt="شارژ ارزان ایرانسل، شارژ ارزان همراه اول و شارژ ارزان رایتل" />
<div class="ribbon animated infinite pulse">
<span>2 درصد تخفیف</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#section Scripts {
<partial name="_ValidationScriptsPartial" />
<script>
$("#rblOperators").change(function () {
var checkedRadio = $("#rblOperators input:checked");
var operatorId = checkedRadio.val();
var ddl = $("##Html.IdFor(model => model.ProductId)");
$.ajax({
cache: false,
url: "#(Url.Action("GetTopupListByOperator", "Topup"))",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
"operatorId": operatorId
},
success: function (data, textStatus, jqXHR) {
ddl.html('');
$.each(data, function (i, option) {
ddl.append($("<option></option>").val(option.id).html(option.name).data("desc", option.desc));
});
}
})
});
--jquery code for show/hide elements or get data from controller
</script>
}
My controller action:
[HttpPost]
public virtual IActionResult Sale(SaleModel saleModel, string submit)
{
switch (submit)
{
case "Cash":
break;
case "Credit":
break;
}
return View();
}
for example after submitting form, productid=0 and mobile is empty.
I have a button before submit buttons and on click form validation occurred and model was being cleaned. I changed button type to submit and used form validation in controller.

Failed to create new data into the database using the popup form

I was trying to create a popup system to create new data into the database. when I click"Create" in my index view then I find a popup form.but when I click "Save" for data save then it does not work anything. suddenly it works and saves the data into the database. but it happened just one time. but I don't understand why it's not working smoothly.
Here is my code:
Model
namespace Practise.Models
{
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
}
}
Controller:
namespace Practise.Controllers
{
public class CategoryController : Controller
{
private ApplicationDbContext _db;
public CategoryController(ApplicationDbContext db) //input parameter
{
_db = db;
}
public IActionResult Index()
{
return View(_db.Category.ToList());
}
[HttpGet]
public IActionResult Create()
{
Category ca = new Category();
return PartialView("_CreatePartial", ca);
//return View();
}
[HttpPost]
public IActionResult Create(Category ca)
{
_db.Category.Add(ca);
_db.SaveChanges();
return PartialView("_CreatePartial", ca);
}
}
}
Index.cshtml
#model IEnumerable<Practise.Models.Category>
#{
ViewData["Title"] = "Index";
}
<div id="PlaceHolderHere"></div>
<button type="button" class="btn btn-primary" data-toggle="ajax-model" data-target="#addEmployee" data-url="#Url.Action("Create")">Create</button>
</br></br>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.CategoryName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
<partial name="_ButtonPartial" model="#item.Id" />
</td>
</tr>
}
</tbody>
</table>
#section scripts{
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/alertify.min.js"></script>
<script type="text/javascript">
$(function(){
var save = '#TempData["save"]'
if (save!= null) {
alertify.success(save);
}
})
</script>
}
_CreatePartial view:
#model Category
<div class="modal fade" id="#addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="#addEmployeeLabel">Add Category</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<div class="form-group">
<label asp-for="CategoryName"> </label>
<input asp-for="CategoryName" class="form-control" />
<span asp-validation-for="CategoryName" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
JS(site.js)
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-model"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
PlaceHolderElement.find('.modal').modal('hide');
})
})
})
My Output:
when I press the save button I want it to save the data to DB.but it does not work.
I have to change something like that for save data:
public IActionResult Create()
{
//Category ca = new Category();
//return PartialView("_CreatePartial", ca);
return View();
}
[HttpPost]
public IActionResult Create(Category ca)
{
_db.Category.Add(ca);
_db.SaveChanges();
return RedirectToAction("Index");
}
Create View:
#model Practise.Models.Category
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<div class="modal fade" id="#addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="#addEmployeeLabel">Add Category</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="CategoryName"> </label>
<input asp-for="CategoryName" class="form-control" />
<span asp-validation-for="CategoryName" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
#*<button type="button" class="btn btn-primary" data-save="modal">Save</button>*#
<input type="submit" class="btn btn-primary" value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
then successfully will save data.

Why would a bool value not be displaying in view correctly?

I have a bool value that I'm using to distinguish between the first item in a series of other items being saved to a link table in my DB. The constructor for the ViewModel sets this to true by default. When my ViewModel is posted to the controller my controller action changes this value to false and passes the edited ViewModel back to the View where this value is saved in a hidden field.
The issue I have is that after the value has been changed, my View is still displaying this value as true. Does anyone have any idea where I'm going wrong?
I also have an issue where I reset the values back to default but these are being retained when the view is reloaded after the post action in executed.
ViewModel
public class NewScriptViewModel
{
public Patient Patient { get; set; }
public int PatientId { get; set; }
public int PrescriberId { get; set; }
public int DrugId { get; set; }
public int Qty { get; set; }
public string Directions { get; set; }
public bool FirstItem { get; set; }
public bool NextItem { get; set; }
public int ScriptId { get; set; }
public NewScriptViewModel()
{
FirstItem = true;
NextItem = false;
}
}
View
#model DispensingApp.Models.ViewModels.NewScriptViewModel
#{
ViewData["Title"] = "New Script";
}
<h1>#Model.Patient.FullName</h1>
<h3>HCN : #Model.Patient.HCN</h3>
<hr />
<div class="row">
<br />
<div class="col-12" onload="newScriptItemForm.reset()">
<form id="newScriptItemForm" asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="ScriptId" type="hidden" value="#ViewData["ScriptId"]" />
<input asp-for="DrugId" type="hidden" />
<table id="drugSelectionTable" class="table table-hover">
<thead>
<tr class="table-secondary">
<th></th>
<th>Name</th>
<th>Pack Size</th>
<th>Generic Ingredients</th>
<th>Stock</th>
</tr>
</thead>
</table>
<div class="form-group">
<div><input asp-for="PatientId" type="hidden" /></div>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Patient.Prescriber.FullName" class="control-label"></label>
</div>
<div class="col-4">
#if (Model.FirstItem)
{
<select asp-for="PrescriberId" class="form-control" asp-items="ViewBag.PrescriberId"></select>
}
else
{
<input asp-for="PrescriberId" type="hidden" />
<input type="text" placeholder="#Model.PrescriberId" class="disabled" />
}
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Qty" class="control-label"></label>
</div>
<div class="col-4">
<input asp-for="Qty" class="form-control" />
</div>
<span asp-validation-for="Qty" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Directions" class="control-label"></label>
</div>
<div class="col-4">
<textarea asp-for="Directions" rows="3" class="form-control"></textarea>
</div>
<span asp-validation-for="Directions" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<input asp-for="FirstItem" type="hidden" />
<input id="nextItem" asp-for="NextItem" type="hidden" />
<button id="nextItemBtn" #*type="submit" value="Next Item"*# class="btn btn-primary form-control">Next Item</button>
</div>
<div class="col-2">
<button asp-action="NewScript" class="btn btn-success form-control">Next Script</button>
</div>
<div class="col-2">
<a asp-controller="Patients" asp-action="Details" asp-route-id="#Model.PatientId" class="btn btn-danger form-control">Cancel</a>
</div>
</div>
</form>
</div>
</div>
Controller Post
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(NewScriptViewModel viewModel,
[Bind("PatientId, PrescriberId")] Script script,
[Bind("DrugId, Qty, Directions")] ScriptDrug scriptDrug)
{
if (ModelState.IsValid)
{
//if first item of script -- create script entry
if (viewModel.FirstItem)
{
_context.Script.Add(script);
await _context.SaveChangesAsync();
viewModel.ScriptId = script.Id;
viewModel.FirstItem = false;
}
scriptDrug.ScriptId = (int)viewModel.ScriptId;
var drug = _context.Drug.Find(scriptDrug.DrugId);
drug.StockQty -= scriptDrug.Qty;
_context.ScriptDrug.Add(scriptDrug);
await _context.SaveChangesAsync();
return await Create(script.PatientId, viewModel);
}
viewModel.NextItem = false;
return await Create(script.PatientId, viewModel);
}
Controller Get
public async Task<IActionResult> Create(int id, NewScriptViewModel viewModel)
{
var patient = await _context.Patient.FindAsync(id);
var vm = new NewScriptViewModel();
//if not first item, reset view model but retain script id
if (!viewModel.FirstItem)
{
vm = viewModel;
}
vm.Patient = patient;
vm.PatientId = patient.Id;
return View(vm);
}
The HTML that is rendered to the browser after all of this looks like:
<div class="col-2">
<input type="hidden" data-val="true" data-val-required="The FirstItem field is required." id="FirstItem" name="FirstItem" value="True">
<input id="nextItem" type="hidden" data-val="true" data-val-required="The NextItem field is required." name="NextItem" value="True">
<button id="nextItemBtn" class="btn btn-primary form-control">Next Item</button>
</div>

Categories

Resources