Asp.NET Pass list of checked items to controller - html

I'm missing something here. I have a table of items with checkboxes that I want to be able to select items from and then send that list of checked items to the controller. I can't get anything passed to the controller. I want a list or array that I can use in the controller.
Here is what I have:
#model Recipe2Grocery.ViewModels.GroceryListViewModel
#{
ViewBag.Title = "Index";
}
#section Scripts{
<style type="text/css">
table {
color: white;
}
</style>
}
<div style="margin: 20px;">
#using (Html.BeginForm("Index", "RecipeIngredient", FormMethod.Post))
{
<table class="table">
<tr>
<th></th>
<th>
Quantity
</th>
<th>
IngredientName
</th>
<th>
Category
</th>
#foreach (var item in Model.ShoppingList)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.IsChecked)
</td>
<td>
#Html.DisplayFor(modelItem => item.Ingredient.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.Ingredient.IngredientName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Ingredient.Category)
</td>
</tr>
}
</table>
<input type="submit" />
}
Then I have a viewmodel as such:
public class ListItem
{
public bool IsChecked { get; set; }
public RecipeIngredient Ingredient { get; set; }
public ListItem()
{
Ingredient = new RecipeIngredient();
}
}
public class GroceryListViewModel
{
public List<ListItem> ShoppingList { get; set; }
public GroceryListViewModel()
{
ShoppingList = new List<ListItem>();
}
}
Then my controller wants to be something like:
[HttpPost]
public ActionResult Index(GroceryListViewModel vm)
{
// blah
return RedirectToAction("Index", "Home");
}

Related

not-null property references a null or transient value ERROR

i'M HAVING A TROUBLE WITH AN PROJECT, AN EXCEPTIONS IS RETURNED TO ME, I tried editing the model by trying to remove the nullable = true constraint, but the porblem persists
org.hibernate.PropertyValueException: not-null property references a null or transient
value
nested exception is org.hibernate.PropertyValueException: not-null property references
a null or transient value
org.springframework.dao.DataIntegrityViolationException: not-null property references a
null or transient value :
I attach below the structure of my project
Controller
#Controller
public class TemperatureController {
#Autowired
private TemperatureService temperatureService;
#RequestMapping(value="/", method= RequestMethod.GET) // inserisco il controllo per la
chiamata alla pagina principale
public ModelAndView homePage() { // creo un modelandview
ModelAndView mv = new ModelAndView(); // creo un'istanza del modelandView
mv.setViewName("home"); // setto il nome dell'istanza
List<InfoMeteo> listaIndicatoriMeteo = temperatureService.getAll();
mv.addObject("listaIndicatoriMeteo",listaIndicatoriMeteo);
mv.addObject("indicatoreMeteo", new InfoMeteo()); // creo la lista
return mv; // ritorno l'istanza
}
#RequestMapping(value="/", method= RequestMethod.POST)
public ModelAndView saveIndicatoriMeteo(InfoMeteo indicatoreMeteo) {
temperatureService.saveIndicatoriMeteo(indicatoreMeteo);
return new ModelAndView("redirect:/");
}
}
Model
#Entity
#Table(name="gestioneindicatorimeteo")
public class InfoMeteo implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO) // uso l'autoincrement
private long id;
#Column(name="Data")
private Date Data;
#Column(name="TemperaturaMax", nullable= false)
private byte TemperaturaGiornalieraMax;
#Column(name="TemperaturaMin", nullable= false)
private byte TemperaturaGiornalieraMin;
#Column(name="precipitazioni")
private String precipitazioni;
#Column(name="Quantità", nullable= false)
private byte quantitaprec;
#Column(name="Tempo", nullable= false)
private String tempo;
#Column(name="URMax", nullable= false)
private byte umiditaMax;
#Column(name="URMin", nullable= false)
private byte umiditaMin;
#Column(name="WSPDMax", nullable= false)
private short velocitaVentoMax;
#Column(name="WSPDMin", nullable= false)
private short velocitaVentoMin;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getData() {
return Data;
}
public void setData(Date data) {
Data = data;
}
public byte getTemperaturaGiornalieraMax() {
return TemperaturaGiornalieraMax;
}
public void setTemperaturaGiornalieraMax(byte temperaturaGiornalieraMax) {
TemperaturaGiornalieraMax = temperaturaGiornalieraMax;
}
public byte getTemperaturaGiornalieraMin() {
return TemperaturaGiornalieraMin;
}
public void setTemperaturaGiornalieraMin(byte temperaturaGiornalieraMin) {
TemperaturaGiornalieraMin = temperaturaGiornalieraMin;
}
public String getPrecipitazioni() {
return precipitazioni;
}
public void setPrecipitazioni(String precipitazioni) {
this.precipitazioni = precipitazioni;
}
public byte getQuantitaprec() {
return quantitaprec;
}
public void setQuantitaprec(byte quantitaprec) {
this.quantitaprec = quantitaprec;
}
public String getTempo() {
return tempo;
}
public void setTempo(String tempo) {
this.tempo = tempo;
}
public byte getUmiditaMax() {
return umiditaMax;
}
public void setUmiditaMax(byte umiditaMax) {
this.umiditaMax = umiditaMax;
}
public byte getUmiditaMin() {
return umiditaMin;
}
public void setUmiditaMin(byte umiditaMin) {
this.umiditaMin = umiditaMin;
}
public short getVelocitaVentoMax() {
return velocitaVentoMax;
}
public void setVelocitaVentoMax(short velocitaVentoMax) {
this.velocitaVentoMax = velocitaVentoMax;
}
public short getVelocitaVentoMin() {
return velocitaVentoMin;
}
public void setVelocitaVentoMin(short velocitaVentoMin) {
this.velocitaVentoMin = velocitaVentoMin;
}
}
Repository
#Repository("TemperatureRepository")
public interface TemperatureRepository extends JpaRepository<InfoMeteo, Long> {
}
Service
public interface TemperatureService {
void saveIndicatoriMeteo(InfoMeteo indicatoreMeteo);
List<InfoMeteo> getAll();
}
Service implementation
#Service("TemperatureService")
public class TemperatureServiceImpl implements TemperatureService {
#Autowired
private TemperatureRepository temperatureRepository; // inietto per dipendenza il
service del repository
#Override
public void saveIndicatoriMeteo(InfoMeteo indicatoreMeteo) {
temperatureRepository.save(indicatoreMeteo);
}
#Override
public List<InfoMeteo> getAll() {
return temperatureRepository.findAll();
}
}
Home.html
<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Home Page</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js">
</head>
<body>
<div class="container">
<div class="pb-3 mt-4 mb-2">
<div class = "btn btn-primary" >
</div>
<h2>Gestione Meteo - <small>Lista Indicatori Meteo</small></h2>
</div>
</div>
<div class="col-md-5" style="margin-top:50px;margin-bottom:50px;">
<form method="post" th:action="#{/}" th:object = "${indicatoreMeteo}">
<div class="form-group">
<label for= "data">Data</label>
<input type="text" " field="*{Data}" id="data>
class="form-control" required>
</div>
<div class="form-group">
<label for= "TemperaturaMax">Temperatura Max</label>
<input type="text" field="*{TemperaturaGiornalieraMax}" id="TemperaturaMax"
class="form-control" required>
</div>
<div class="form-group">
<label for= "TemperaturaMin">Temperatura Min</label>
<input type="text" id="TemperaturaMin"
field="*{TemperaturaGiornalieraMin}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "precipitazioni">Precipitazioni (prp)</label>
<input type="text" id="precipitazioni"
field="*{precipitazioni}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "Quantità">Quantità precipitazioni</label>
<input type="text" id="Quantità"
field="*{quantitaprec}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "Tempo">Condizioni meteo</label>
<input type="text" id="Tempo"
field="*{tempo}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "URMax">Ur max (Umidità)</label>
<input type="text" id="URMax"
field="*{umiditaMax}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "URMin">Ur Min (Umidità)</label>
<input type="text" id="URMin"
field="*{umiditaMin}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "WSPDMax">Velocità vento Min (Wv)</label>
<input type="text" id="WSPDMax"
field="*{velocitaVentoMax}"
class="form-control" required>
</div>
<div class="form-group">
<label for= "WSPDMin">Velocità vento Max(Wv)</label>
<input type="text" id="WSPDMin"
field="*{velocitaVentoMin}"
class="form-control" required>
</div>
<button style="margin-top:50px;" type="submit"
class="btn btn-dark"> Salva indicatori Meteo</button>
</form>
</div>
<table class="table table-striped">
<div table= "pb-2 mt-4 mb-3">
<thead>
<tr>
<th scope="col">Data</th>
<th scope="col">Temperatura Max giornaliera</th>
<th scope="col">Temperatura Min giornaliera</th>
<th scope="col">precipitazioni</th>
<th scope="col">Tipo di precipitazioni</th>
<th scope="col">Quantita prec </th>
<th scope="col">Condizioni meteo</th>
<th scope="col">Umidita Max</th>
<th scope="col">Umidita Min</th>
<th scope="col">Velocita Vento Max</th>
<th scope="col">Velocita Vento Min</th>
</tr>
<tbody>
<tr th:each="indicatoreMeteo: ${listaIndicatoriMeteo}">
<td th:text= "${indicatoreMeteo.Data}"></td>
<td th:text= "${indicatoreMeteo.TemperaturaGiornalieraMax}"></td>
<td th:text= "${indicatoreMeteo.TemperaturaGiornalieraMin}"></td>
<td th:text= "${indicatoreMeteo.precipitazioni}"></td>
<td th:text= "${indicatoreMeteo.quantitaprec}"></td>
<td th:text= "${indicatoreMeteo.tempo}"></td>
<td th:text= "${indicatoreMeteo.umiditaMax}"></td>
<td th:text= "${indicatoreMeteo.umiditaMin}"></td>
<td th:text= "${indicatoreMeteo.velocitaVentoMax}"></td>
<td th:text= "${indicatoreMeteo.velocitaVentoMin}"></td>
</tbody>
</table>
I have tried different solutions but it keeps giving me this kind of exception all the time, I don't know what to do

Server Error in '/' Application. ASP.Net MVC Visual Studio 2019

Whenever I run the program, it works perfectly. However, as soon as I hit the "Login" button it tells me
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /LoginController/Authorize
I checked everything and the spelling is correct. I am new to this and cannot figure out what I am doing wrong. Any guidance would be highly appreciated it.
Inside of the App_Start folder I have my RouteConfig.cs file. It contains the following:
namespace CoffeeShop_Web_App
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "LoginController", action = "Index", id = UrlParameter.Optional }
);
}
}
}
I have one controller which is my LoginController.cs which contains the following.
namespace CoffeeShop_Web_App.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Authorize()
{
return View();
}
}
}
Lastly, my only view Index.cshtml which contains the following.
#model CoffeeShop_Web_App.Models.OwnerLogin
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<style>
#login-div {
position: absolute;
left: 40%;
top: 40%;
border: 1px solid #ccc;
padding: 10px 10px;
}
</style>
</head>
<body>
<div id="login-div">
#using (Html.BeginForm("Authorize", "LoginController", FormMethod.Post))
{
<table>
<tr>
<td></td>
<td style="text-decoration:underline">Coffee Shop</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.USERNAME)
</td>
<td>
#Html.EditorFor(model => model.USERNAME)
</td>
</tr>
<tr>
<td></td>
<td>#Html.ValidationMessageFor(model => model.USERNAME)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.PASSWORD)
</td>
<td>
#Html.EditorFor(model => model.PASSWORD)
</td>
</tr>
<tr>
<td></td>
<td>#Html.ValidationMessageFor(model => model.PASSWORD)</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="name" value="Login" />
<input type="reset" name="name" value="Clear" />
</td>
</tr>
</table>
}
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
Your form is posting back to the Authorize method of LoginController controller:
#using (Html.BeginForm("Authorize", "LoginController", FormMethod.Post))
You don't have to specify controller suffix for the name of the controller. The following should fix it:
#using (Html.BeginForm("Authorize", "Login", FormMethod.Post))
Also you did the same mistake when setting up the routing too:
defaults: new { controller = "LoginController", action = "Index",
id = UrlParameter.Optional }
which should have been just:
defaults: new { controller = "Login", action = "Index",
id = UrlParameter.Optional }

How to pass button value from a modal window (that uses partial view) to the parent view

here is the button on the partial view,
<button type="button" name="btnid" id="bparentid" value="#item.Itemid " class="btn btn-success" onclick="alert(#item.Itemid)">Select</button>
Just to check if it holds the value I put razor alert function, and I want the button value to be passed to the parent view on button click using this hidden input form in the parent view
<input asp-for="Itemid" type="hidden" value=" #item.Itemid" />
More detail:
I have two tables for recording children and their parents separately,
Here is the Model
public class Children
{
[Key]
public int ChildID { get; set; }
[Required] [StringLength(50)]
public string FirstName { get; set; }
[ForeignKey("Parentid")]
public virtual Parent Parent { get; set; }
}
public class Parent
{
[Key]
public int Parentid { get; set; }
public string FullName { get; set; }
public virtual IEnumerable<Children> Children { get; set; }
}
And here is the Create method controller for posting new children record with their parent information:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ChildID,FirstName")] Children children, int existingParentid,
[Bind("Parentid,FullName")] Parent parent, bool existingparent)
{
if (ModelState.IsValid)
{
if (existingparent)
{
children.Parentid = existingParentid;
_context.Add(children);
await _context.SaveChangesAsync();
return View(children);
}else
_context.Add(children);
await _context.SaveChangesAsync();
_context.Add(parent);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(children);
}
Here is the controller method for the modal partial view
public async Task<IActionResult> ModalAction()
{
var MyDbContext = _context.Children.Include(C => C.Parent);
return PartialView(await MyDbContext.ToListAsync());
}
And here is the view for the Create method
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
#Html.ActionLink("Select Existing Parent", "ModalAction", "Children", null, new { #class = "btn btn-flat margin",
data_target = "#searchparent", data_toggle = "modal" })
<input asp-for="Parentid" type="hidden" value=" " />
<div class="modal fade" id="searchparent">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Parent.FullName" class="control-label"></label>
<input asp-for="Parent.FullName" class="form-control" />
<span asp-validation-for="Parent.FullName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
Here is the modal partial view
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Search for Parent data table </h4>
</div>
<div class="modal-body">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
<button type="button" name="bparentid" id="bparentid" value="#item.ChildID" class="btn btn-block btn-success btn-xs"
onclick="alert(#item.ChildID)">
Select
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
The Question:
How can I pass the #item.ChildID value from the partial view to the Create view which will then pass it as hidden value to the create controller
Since you are trying to change the value of the input field after the page has loaded, this needs to happen inside the user's browser, so Razor which runs server-side can't help. But you can accomplish what you want using javascript:
//First add an ID to your hidden input
<input id="my-input" ... />
//Second add the following onclick to your button:
<button onclick="document.getElementById('my-input').value = this.value" ...></button>

How to format dynamic controls in MVC 5

In the following code from my MVC 5 View, I am dynamically building label and textbox controls but I need to format them in a table so I am not sure how I can do this.
#using InFlowConvertWeb.WebUI.Models
#model InFlowConvertWeb.WebUI.Models.SearchControlListViewModel
#{
ViewBag.Title = "List";
}
#using (Html.BeginForm())
{
int searchControlIndex = 0;
foreach (SearchControl searchControl in Model.SearchControls)
{
switch (searchControl.ControlType)
{
case SearchControl.ControlTypes.TextBox:
{
<div class="form-group" style="margin-left: 15px">
#Html.Label(searchControl.FieldName,
new { #class = "col-md-12 control-label" })
#Html.TextBoxFor(
x => x.SearchControls[searchControlIndex].SearchValue)
#Html.HiddenFor(x => x.SearchControls[searchControlIndex].DataTable)
#Html.HiddenFor(x => x.SearchControls[searchControlIndex].FieldName)
</div>
break;
}
}
searchControlIndex += 1;
}
<div class="col-md-2">
<h2>
<input type="submit" value="Submit Selections" />
</h2>
</div>
Any suggestions would be greatly appreciated,
Bob
Try this Example:
#using InFlowConvertWeb.WebUI.Models
#model InFlowConvertWeb.WebUI.Models.SearchControlListViewModel
#{
ViewBag.Title = "List";
}
#using (Html.BeginForm())
{
<table id="dataTable" class="table table-bordered table-hover">
<tbody>
#{int searchControlIndex = 0;}
#foreach (SearchControl searchControl in Model.SearchControls)
{
switch (searchControl.ControlType)
{
case SearchControl.ControlTypes.TextBox:
{
<tr>
<td>
#Html.Label(searchControl.FieldName, new { #class = "col-md-12 control-label" })
</td>
<td>
#Html.TextBoxFor(x =>x.SearchControls[searchControlIndex].SearchValue)
#Html.HiddenFor(x =>x.SearchControls[searchControlIndex].DataTable)
#Html.HiddenFor(x =>x.SearchControls[searchControlIndex].FieldName)
</td>
</tr>
break;
}
}
searchControlIndex += 1;
}
</tbody>
</table>
<div class="col-md-2">
<h2> <input type="submit" value="Submit Selections" /> </h2>
</div>
}

pass a parameter into named query

I have the following query in my model(Supplier) class :
#NamedQuery(name = "Supplier.findSupplierKeyId", query = "SELECT s FROM Supplier s WHERE s.supplierid LIKE (':supplieridkey%')")
I have following function in my Controller(SupplierSerivce) class:
public List<Supplier> findSupplierKeyId(String supplierkeyid){
List<Supplier> supplierList = mgr.createNamedQuery("Supplier.findSupplierKeyId").setParameter("supplieridkey", supplierkeyid).getResultList();
return supplierList;
}
I want to get in a html textfield :
<form action="SearchSupplierIdKey.jsp" method="POST">
<div>
<input type="text" name="supIdKey"/>
<input type="submit" value="Search" name="button"/>
</div>
</form>
then get parameter from the textfield and pass it into supService.findSupplierKeyId through servlet:
public class SearchSupplierIdKey extends HttpServlet {
#PersistenceContext
EntityManager em;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
SupplierService supService = new SupplierService(em);
HttpSession session = request.getSession();
String supId = (String) session.getAttribute("supId");
String button = (String) session.getAttribute("button");
List<Supplier> supplierListResult = supService.findSupplierKeyId(supId);
session.setAttribute("supplierListResult", supplierListResult);
if (button.equals("Search")) {
response.sendRedirect("ViewSupplierByIdKey.jsp");
}
} catch (Exception ex) {
Logger.getLogger(AddSupplier.class.getName()).log(Level.SEVERE, null, ex);
}
}
Then show the result in ViewSupplierByIdKey.jsp :
<%#page import="java.util.List"%>
<%#page import="model.Supplier"%>
<!-- retrieve session object, itemList -->
<%
List<Supplier> supplierListResult = (List)session.getAttribute("supplierListResult");
%>
<html>
<head>
<title>Supplier Search Result</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<table cellspacing="0" cellpadding="0" style="margin-left:auto; margin-right:auto; border:solid; width: 1000px">
<tr style="border:solid">
<td style="border:solid ">
<h3 style="text-align: center">ABC Health Supplement Shop System</h3>
</td>
</tr>
<tr style="border: solid">
<td style="border: solid">
<center><h1><i><b><font face="Segoe Script" color="#FF0000">Supplier Search Result(By ID Key)</font></b></i></h1></center>
</td>
</tr>
<tr style="border:solid">
<td style="border:solid">
<center><div>
<table border="1">
<tr>
<th>Supplier ID</th>
<th>Supplier Name</th>
<th>Manufacturer</th>
<th>Contact Num</th>
<th>Address</th>
</tr>
<% for (Supplier supplier: supplierListResult){ %>
<tr>
<td><%= supplier.getSupplierid() %></td>
<td><%= supplier.getSuppliername()%> </td>
<td><%= supplier.getManufacturer()%> </td>
<td><%= supplier.getContactnum()%> </td>
<td><%= supplier.getAddress()%> </td>
</tr>
<% } %>
</table>
<br><br>
<p>Back to Menu page</p>
</div>
</center>
</td>
</tr>
</table>
</body>
</html>
but i dont knw why i cant proceed to ViewSupplierByIdKey.jsp, it stuck at the controller class
(SearchSupplierIdKey.java). Please Help :( :(
One thing that I notice is the request parameter is retrieved using the name supId:
String supId = (String) session.getAttribute("supId");
but specified as supIdKey in the HTML:
<input type="text" name="supIdKey"/>
The name attribute used on the input should match the key being used to retrieve the attribute.