I'm using mybatis, but the select value is null - spring-boot

I have configured a simple member login and the search return value is null
In DAO, the return value of selectOne in sqlSession is null.
insert statement works fine
can i know the solution?
loginPage.html
<form action="/memberLogin" method="post" class="login100-form validate-form">
<div class="wrap-input100 validate-input m-b-26" data-validate="Username is required">
<span class="label-input100">Username</span>
<input class="input100" type="text" name="member_name" placeholder="Enter username">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input m-b-18" data-validate = "Password is required">
<span class="label-input100">Password</span>
<input class="input100" type="password" name="member_pwd" placeholder="Enter password">
<span class="focus-input100"></span>
</div>
<div class="flex-sb-m w-full p-b-30">
<div class="contact100-form-checkbox">
<input class="input-checkbox100" id="ckb1" type="checkbox" name="remember-me">
<label class="label-checkbox100" for="ckb1">
Remember me
</label>
</div>
<div>
<a href="#" class="txt1">
Forgot Password?
</a>
</div>
</div>
<div class="container-login100-form-btn">
<button type="submit" class="login100-form-btn">
login
</button>
<button type="button" id = "loginBtn" class="login100-form-btn"><a href="/signUp">
signUp</a>
</button>
</div>
</form>
MemberController
#PostMapping(value = "/memberLogin")
public String login(MemberDTO memberDTO, HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
session.setMaxInactiveInterval(3600);
System.out.println("세션 아이디 : " + session.getId());
System.out.println("세션 유효시간 : " + session.getMaxInactiveInterval());
System.out.println("memberDTO : " + memberDTO);
MemberDTO member = memberService.login(memberDTO);
System.out.println("member : " + member);
if (member != null){
session.setAttribute("member", member);
System.out.println("로그인 성공");
return "redirect:/";
} else {
System.out.println("로그인 실패");
return "redirect:login";
}
}
MemberService
#Override
public MemberDTO login(MemberDTO memberDTO) throws Exception {
System.out.println("login Service : " + memberDTO);
return memberDAO.login(memberDTO);
}
MemberDAO
#Override
public MemberDTO login(MemberDTO memberDTO) throws Exception {
MemberDTO member = null;
System.out.println("DAO : " + memberDTO);
member = sqlSession.selectOne(NAMESPACE + "loginCheck", memberDTO);
System.out.println("dao : " + member);
return sqlSession.selectOne(NAMESPACE + "loginCheck", memberDTO);
}
MemberDTO
public class MemberDTO {
private String member_name;
private String member_pwd;
private String member_email;
private String member_role;
private Date member_register_datetime;
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
public String getMember_pwd() {
return member_pwd;
}
public void setMember_pwd(String member_pwd) {
this.member_pwd = member_pwd;
}
public String getMember_email() {
return member_email;
}
public void setMember_email(String member_email) {
this.member_email = member_email;
}
public String getMember_role() {
return member_role;
}
public void setMember_role(String member_role) {
this.member_role = member_role;
}
public Date getMember_register_datetime() {
return member_register_datetime;
}
public void setMember_register_datetime(Date member_register_datetime) {
this.member_register_datetime = member_register_datetime;
}
#Override
public String toString() {
return "MemberDTO{" +
"member_name='" + member_name + '\'' +
", member_pwd='" + member_pwd + '\'' +
", member_email='" + member_email + '\'' +
", member_role='" + member_role + '\'' +
", member_register_datetime=" + member_register_datetime +
'}';
}
}
MemberMapper.xml
<mapper namespace="member">
<insert id = "signUp" parameterType="com.withstudy.domain.MemberDTO">
insert into MEMBER
values (#{member_email, jdbcType = VARCHAR}, #{member_pwd, jdbcType = VARCHAR}, #{member_name, jdbcType = VARCHAR}, 'General', sysdate)
</insert>
<select id = "loginCheck" parameterType="com.withstudy.domain.MemberDTO" resultType="com.withstudy.domain.MemberDTO">
SELECT * FROM MEMBER
WHERE MEMBER_NAME = #{member_name, jdbcType = VARCHAR}
AND MEMBER_PWD = #{member_pwd, jdbcType = VARCHAR}
</select>
</mapper>
Oracle DB(SQL Developer)
enter image description here
Console
enter image description here

It is a good practice to list columns that you are expected to map on your Entity in SELECT statement. You can accidentally pull something big and query performance may degradates. So try to list them first:
SELECT
member_name,
member_pwd,
member_email,
member_role,
member_register_datetime;
FROM MEMBER
WHERE MEMBER_NAME = #{member_name, jdbcType = VARCHAR}
AND MEMBER_PWD = #{member_pwd, jdbcType = VARCHAR}

Related

I can't get left join result to view with pagination

i can't pass the result to view, my Index view has pagination.
Index View:
#model rInventarioTI.Clases.PaginationList<rInventarioTI.Models.Productos>
#{
ViewData["Title"] = "Lista Productos";
}
<h1 class="text-center">Listado Productos</h1>
<br />
<br />
<br />
<form asp-action="Index" method="get">
<div class="form-group d-flex justify-content-center">
<p>
Tipo/Serie/Marca/Modelo
<input type="text" name="searchString" value="#ViewData["FiltroActual"]" />
<input type="submit" value="Filtrar" class="btn btn-primary" />
<a asp-action="Index">Borrar filtro</a>
</p>
</div>
</form>
<p class="float-end">
<a asp-action="Create" class="btn btn-success">Crear nuevo</a>
</p>
<table class="table">
<thead class="bg-dark" style="color: white;">
<tr>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["TypeProductNameSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Tipo de producto <i class="fas fa-sort-amount-down-alt"></i> </a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["COGSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">COG <i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["SerieSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Numero de Serie <i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["MarcaSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Marca <i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["ModeloSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Modelo Equipo<i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
#*#Html.DisplayNameFor(model => model.TiposMovimientosNav)*#
Movimiento
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["DateSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Fecha Registro<i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>Operaciones</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.TiposProductosNav.Nombre)
</td>
<td>
#Html.DisplayFor(modelItem => item.COG)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumeroSerie)
</td>
<td>
#Html.DisplayFor(modelItem => item.MarcasNav.Nombre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Modelo)
</td>
<td>
#Html.DisplayFor(modelItem => item.MovimientosProductosNav)
</td>
<td>
#Html.DisplayFor(modelItem => item.FechaAlta)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id"><i class="fas fa-pencil-alt"></i></a> |
<a asp-action="Details" asp-route-id="#item.Id"><i class="fas fa-eye"></i></a> |
<a asp-action="Delete" asp-route-id="#item.Id"><i class="fas fa-trash-alt"></i></a> |
<a asp-action="Asignar" asp-route-id="#item.Id"><i class="fas fa-arrow-right"> Asignar</i></a> |
<a asp-action="Desasignar" asp-route-id="#item.Id"><i class="fas fa-arrow-left"> Desasignar</i></a> |
<a asp-action="Transferir" asp-route-id="#item.Id"><i class="fas fa-exchange-alt"> Transferir</i></a>
</td>
</tr>
}
</tbody>
</table>
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<a asp-action="Index"
asp-route-sortOrder="#ViewData["OrdenamientoActual"]"
asp-route-pageNumber="#(Model.PageIndex + 1)"
asp-route-filtroActual="#ViewData["FiltroActual"]"
class="btn btn-primary #nextDisabled float-end">Adelante</a>
<a asp-action="Index"
asp-route-sortOrder="#ViewData["OrdenamientoActual"]"
asp-route-pageNumber="#(Model.PageIndex - 1)"
asp-route-filtroActual="#ViewData["FiltroActual"]"
class="btn btn-primary #prevDisabled float-end">Atrás</a>
PaginationList
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace rInventarioTI.Clases
{
public class PaginationList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginationList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginationList<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 PaginationList<T>(items, count, pageIndex, pageSize);
}
}
}
Productos Model:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace rInventarioTI.Models
{
//[Index(nameof(COG), IsUnique = true)]
public partial class Productos
{
public Productos()
{
MovimientosProductosNav = new HashSet<MovimientosProductos>();
}
public int Id { get; set; }
[Display(Name = "Tipo de producto")]
//[Required(ErrorMessage = "Seleccione un tipo de producto")]
public int TiposProductosID { get; set; }
[Display(Name = "Marca")]
public int MarcasID { get; set; }
// Algunos productos pueden no tener numero de serie.
[Display(Name = "Numero Serie")]
public string NumeroSerie { get; set; }
[Display(Name = "Descripcion")]
[Required(ErrorMessage = "Ingrese una descripción")]
[StringLength(1500, MinimumLength = 6, ErrorMessage = " Caracteres permitidos, mas de 6 y menos de 1500")]
public string Descripcion { get; set; }
[Display(Name = "Modelo del producto")]
[Required(ErrorMessage = "Ingrese un modelo para este producto")]
public string Modelo { get; set; }
[Display(Name = "Color de producto")]
[Required(ErrorMessage = "Ingrese un color para este producto")]
public string Color { get; set; }
[Display(Name = "Codigo del fabricante")]
public string CodigoFabricante { get; set; }
// Clave unica e irrepetible. TODOS los productos deben tener
// un COD definido y asignado por el sistema.
[Display(Name = "COG")]
[Required(ErrorMessage = "Ingrese un COG")]
[StringLength(25, MinimumLength = 3, ErrorMessage = "Ingrese un COG de entre 3 y 25 caracteres")]
public string COG { get; set; }
[Display(Name = "Datos QR del producto")]
public string CodigoQr { get; set; }
[Display(Name = "Fecha de Registro")]
public DateTime FechaAlta { get; set; }
[Display(Name = "Tipo de producto")]
public virtual TiposProductos TiposProductosNav { get; set; }
[Display(Name = "Marcas")]
public virtual Marcas MarcasNav { get; set; }
public virtual ICollection<MovimientosProductos> MovimientosProductosNav { get; set; }
}
}
MovimientosProductos Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace rInventarioTI.Models
{
public partial class MovimientosProductos
{
public MovimientosProductos() {
}
public int id { get; set; }
[Required]
public int ProductosID { get; set; }
[Display(Name = "Tipo Movimiento")]
[Required]
public int TiposMovimientosID { get; set; }
[Display(Name = "Usuario Genera Movimiento")]
public int UsuariosID { get; set; }
[Display(Name = "Oficina Destino")]
public int OficinasID { get; set; }
[Display(Name = "Estado físico del producto")]
public int EstadosProductosID { get; set; }
[Display(Name = "Observaciones del movimiento y/o producto")]
[Required(ErrorMessage = "Observaciones del movimiento y/o producto")]
[StringLength(1500, MinimumLength = 6, ErrorMessage = "Minimo 6 caracteres, maximo 1500 caracteres.")]
public string Observaciones { get; set; }
[Display(Name = "Fotos del producto")]
public string PathFotos { get; set; }
[Display(Name = "Fecha de Registro")]
public DateTime FechaAlta { get; set; }
[Display(Name = "Produco")]
public virtual Productos ProductosNav { get; set; }
[Display(Name = "Tipo Movimiento")]
public virtual TiposMovimientos TiposMovimientosNav { get; set; }
[Display(Name = "Usuario generó movimiento")]
public virtual Usuarios UsuariosNav { get; set; }
[Display(Name = "Oficina asignada")]
public virtual Oficinas OficinaNav { get; set; }
[Display(Name = "Estado del producto")]
public virtual EstadosProductos EstadosProductosNav { get; set; }
}
}
Productos Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using rInventarioTI.Models;
using rInventarioTI.Clases;
using System.Collections.Generic;
//using System.Data.Entity;
namespace rInventarioTI.Controllers
{
public class ProductosController : Controller
{
private readonly rInventarioContext _context;
public ProductosController(rInventarioContext context)
{
_context = context;
}
// GET: Productos
public async Task<IActionResult> Index(
string sortOrder,
string filtroActual,
string searchString,
int? pageNumber)
{
ViewData["OrdenamientoActual"] = sortOrder;
ViewData["TypeProductNameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
ViewData["COGSortParm"] = sortOrder == "COG" ? "COG_desc" : "COG";
ViewData["SerieSortParm"] = sortOrder == "Serie" ? "Serie_desc" : "Serie";
ViewData["MarcaSortParm"] = sortOrder == "Marca" ? "Marca_desc" : "Marca";
ViewData["ModeloSortParm"] = sortOrder == "Modelo" ? "Modelo_desc" : "Modelo";
ViewData["DatesortParm"] = sortOrder == "Date" ? "Date_desc" : "Date";
// Valido si hay cadena de búsqueda ingresada
if (searchString != null)
{
pageNumber = 1;
} else
{
searchString = filtroActual;
}
ViewData["FiltroActual"] = searchString;
//var productos = (from prod in _context.Productos
// select prod)
// .Include(m => m.MarcasNav).AsQueryable()
// .Include(t => t.TiposProductosNav).AsQueryable()
// .Include(ep => ep.MovimientosProductosNav).AsQueryable();
/*
Recupera listado de productos, donde el numero de movimientos sea de 2 o mas.
*/
var productos = (from prod in _context.Productos.ToList()
join mov in _context.MovimientosProductos on prod.Id equals mov.ProductosID into ProductosMovimientosGroup
from mov in ProductosMovimientosGroup.DefaultIfEmpty()
where (ProductosMovimientosGroup.Count() == 0)
select prod);
if (!String.IsNullOrEmpty(searchString))
{
productos = productos.Where(
prod => prod.TiposProductosNav.Nombre.Contains(searchString) ||
//prod.SerialesProductosID.
prod.MarcasNav.Nombre.Contains(searchString) ||
prod.Modelo.Contains(searchString) ||
prod.COG.Contains(searchString));
}
switch (sortOrder)
{
case "Name_desc":
productos = productos.OrderByDescending(prod => prod.TiposProductosNav.Nombre);
break;
case "COG":
productos = productos.OrderBy(prod => prod.COG);
break;
case "COG_desc":
productos = productos.OrderByDescending(prod => prod.COG);
break;
case "Serie":
productos = productos.OrderBy(prod => prod.NumeroSerie);
break;
case "Serie_desc":
productos = productos.OrderByDescending(prod => prod.NumeroSerie);
break;
case "Marca":
productos = productos.OrderBy(prod => prod.MarcasNav.Nombre);
break;
case "Marca_desc":
productos = productos.OrderByDescending(prod => prod.MarcasNav.Nombre);
break;
case "Modelo":
productos = productos.OrderByDescending(prod => prod.Modelo);
break;
case "Modelo_desc":
productos = productos.OrderBy(prod => prod.Modelo);
break;
case "Date":
productos = productos.OrderBy(prod => prod.FechaAlta);
break;
case "Date_desc":
productos = productos.OrderByDescending(prod => prod.FechaAlta);
break;
default:
productos = productos.OrderBy(prod => prod.TiposProductosNav.Nombre);
break;
}
int pageSize = 10;
return View(await PaginationList<Productos>.CreateAsync(
productos.AsNoTracking(),
pageNumber ?? 1,
pageSize));
//return View(productos);
}
}
}
Source: Tutorial: Add sorting, filtering, and paging - ASP.NET MVC with EF Core
My query in SQL works fine
Image SQL Script works
SELECT Productos.COG, Productos.Id
from Productos
left join MovimientosProductos on MovimientosProductos.ProductosID = Productos.Id
Group by Productos.Id, Productos.COG
having COUNT(MovimientosProductos.ProductosID) = 0
SELECT Productos.COG, Productos.Id, ProductosID
from MovimientosProductos
RIGHT join Productos on Productos.Id = MovimientosProductos.ProductosID
Group by Productos.COG, Productos.Id, ProductosID
having ProductosID IS NULL
My query in Linq is:
var productos = (from prod in _context.Productos.ToList()
join mov in _context.MovimientosProductos on prod.Id equals mov.ProductosID into ProductosMovimientosGroup
from mov in ProductosMovimientosGroup.DefaultIfEmpty()
where ProductosMovimientosGroup.Count() == 0
select prod);
and in debug mode productos has 3 records. Works fine.
But when the app runs, i get this error:
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable' does not contain a definition
for 'AsNoTracking' and no accessible extension method 'AsNoTracking'
accepting a first argument of type 'IEnumerable' could be
found (are you missing a using directive or an assembly reference?)
I understand that i need to get IQueryable result instead of IEnumerable, but how can i convert the result?
Then, i have removed ToList() from the query and AsNoTracking() from the return View for test, but now the error is:
An unhandled exception occurred while processing the request.
InvalidOperationException: The LINQ expression 'DbSet()
.LeftJoin( inner: DbSet(), outerKeySelector: p
=> p.Id, innerKeySelector: m => m.ProductosID, resultSelector: (p, m) => new TransparentIdentifier<Productos, MovimientosProductos>( Outer = p, Inner = m )) .Where(ti => ProductosMovimientosGroup .Count() == 0)'
could not be translated. Either rewrite the query in a form that can
be translated, or switch to client evaluation explicitly by inserting
a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or
'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for
more information.
But i don't know how to translate the query...
Thank you
Thank you all for your comments
Gert Arnold mentioned the navigation properties and then changed the query for this:
var productos = (from p in _context.Productos
.Include(mp => mp.MovimientosProductosNav)
.Include(m => m.MarcasNav)
.Include(tp => tp.TiposProductosNav).ToList()
select p);
I get the properties by "navigation properties" declared in my models and the view get model without any problem.
Now it works.

How to get the textbox values in Blazor and show it in a span in #onblur event, if multiple textboxes generated using for loop

My requirement is I have 4 textboxes rendered using a for loop on model, when I entered a value and focus out of any text box, I need to capture the value into a variable and show it in a span before submit
I have tried with call a function in blur event
<EditForm EditContext="#EditContext">
<DataAnnotationsValidator />
#for (int j = 0; j < transactionModels.Count; j++)
{
int i = j;
<input type="text" class="form-control"
#bind="transactionModels[i].Amount" #onblur="Getvalue" placeholder="Amount" />
<span>**Textboxvalue** </span>
}
</EditForm>
#code{
public void Getvalue()
{
Textboxvalue= transactionModels.Amount
}
The code below is a demo page showing how to link an array of values into a set of text boxes and have the array update. You should be able to adapt it to your specific circumstances. (I made an assumption that amount is a number, not text).
#page "/"
<h2>Home Page</h2>
<EditForm EditContext="this.editContext">
#foreach (var modelData in _model.data)
{
<div>
<InputNumber #bind-Value="modelData.Amount"></InputNumber>
</div>
<div>
Value: #modelData.Amount
</div>
}
</EditForm>
#code {
public class ModelData
{
public int Amount { get; set; }
}
public class Model
{
public List<ModelData> data = new List<ModelData> {
new ModelData { Amount = 12},
new ModelData { Amount = 10},
new ModelData { Amount = 8},
new ModelData { Amount = 6},
};
}
private EditContext editContext;
protected Model _model { get; set; } = new Model();
protected override Task OnInitializedAsync()
{
editContext = new EditContext(_model);
return base.OnInitializedAsync();
}
}
Stick with #foreach for these situations. If you use #for you need to define a local variable for each loop.
I don't think you really need to use "onblur", which is javascript-minded, not Blazor.
Replace your <input type="text"... by
<InputText type="text" class="form-control" #bind-Value="transactionModels[i].Amount" placeholder="Amount" />
The span should become
<span>#transactionModels[i].Amount </span>
If transactionModels[i].Amount is of numeric type (what is suggested by the name, but not your choice of type="text"), replace <InputText type="text" by <InputNumber.
If it is a string, do not forget to remove special characters to prevent XSS.
Edit after 2nd comment:
In the transactionModel class, add these properties
private double amount;
internal double Amount
{
get => amount;
set
{
LoanRelatedPopupVisible = (value < 0);
DepositRelatedPopup = (value > 0);
amount = value;
}
}
internal bool LoanRelatedPopupVisible { get; set; }
internal bool DepositRelatedPopup { get; set; }
To manage the visibility of the popup
#if (transactionModels[i].LoanRelatedPopupVisible)
{
<div here the popup ...
}

Unable to remove mandatory validation in MVC

I am not an expert MVC programmer but have to make a small change in the code. Any help?
I have a field CallerType which had [required] attribute. However, I do not want to be mandatory anymore so I am removing [required] attribute but still get the same input required error.
public virtual CallType CallType { get; set; }
[Display(Name = "Type of Calls")]
/*Akbar-start*[Required]*Akbar-end*/
public int CallTypeID { get; set; }
<div class="form-group col-3">
<label asp-for="Intake.CallTypeID" class="control-label"></label>
<select asp-for="Intake.CallTypeID"class="form-control">asp-items="Model.CallTypes">
<option value="">Please Select</option>
</select>
<span asp-validation-for="Intake.CallTypeID" class="text-danger"></span>
</div>
Error:
enter image description here
I also see javascript like below but not sure how this is getting invoked:
$('input').each(function () {
var req = $(this).attr('data-val-required');
var hide = $(this).attr('hide-required-indicator');
var hasIndicator = $(this).hasClass('has-required-indicator');
if (undefined != req && undefined == hide && !hasIndicator) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red" class="required-indicator"> *</span>');
$(this).addClass('has-required-indicator');
}
}
});
$('select').each(function () {
var req = $(this).attr('data-val-required');
var hasIndicator = $(this).hasClass('has-required-indicator');
if (undefined != req && !hasIndicator) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
$(this).addClass('has-required-indicator');
}
}
});
I was able to solve this issue.
Here is the trick:
Changed int to int?
public int CallTypeID { get; set; }
i.e.
public int? CallTypeID { get; set; }
? indicates that this field is nullable. It was overriding [Required] attribute

jsf selectOneMenu strange itemValue

In my app I have selectOneMenu to select month.
<h:selectOneMenu value="#{register.monthOfBirth}">
<f:selectItems value="#{register.dateValues.monthsList}" var="month" itemLabel="#{month.valueLabel}" itemValue="#{month.valueValue}"/>
<f:ajax listener="#{register.monthChanged}" render="messages" />
</h:selectOneMenu>
Here's my DateValues class which I use to populate selectOneMenu's:
public class DateValues {
public static class Values{
public String valueLabel;
public String valueValue;
public Values(String valueLabel, String valueValue){
this.valueLabel = valueValue;
this.valueLabel = valueValue;
}
public String getValueLabel(){
return valueLabel;
}
public String getValueValue(){
return valueValue;
}
}
public Values[] daysList;
public Values[] monthsList;
public Values[] yearsList;
public DateValues(){
daysList = new Values[31];
for(int i=0;i<31;i++){
daysList[i] = new Values(""+ (i+1),""+(i+1));
}
monthsList = new Values[12];
for(int i=0;i<12;i++){
monthsList[i] = new Values("" + (i+1),"" + (i+1));
}
yearsList = new Values[109];
Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
int first = currentYear - 108;
for(int i=0;i<109;i++) {
yearsList[i] = new Values("" + (first + (108-i)),"" + (first + (108-i)));
}
}
public Values[] getDaysList() {
return daysList;
}
public Values[] getMonthsList() {
return monthsList;
}
public Values[] getYearsList() {
return yearsList;
}
}
In the #ManagedBean I've got an ajax listener:
public void monthChanged(){
System.out.println("New month is month number " + monthOfBirth);
}
What I get in the output is:
"INFO: New month is month number dyplom.dyplom.date.DateValues$Values#79f6099"
instead of (for example) 2 (number of month, so February)
What did I do wrong?
EDIT:
GENERATED HTML:
<h2><select id="j_idt56:j_idt70" name="j_idt56:j_idt70" size="1" onchange="mojarra.ab(this,event,'valueChange',0,'j_idt56:messages')"> <option value="dyplom.dyplom.date.DateValues$Values#32b0c37e">1</option>
<option value="dyplom.dyplom.date.DateValues$Values#72f29f31">2</option>
<option value="dyplom.dyplom.date.DateValues$Values#16b184ec">3</option>
<option value="dyplom.dyplom.date.DateValues$Values#608dad97">4</option>
<option value="dyplom.dyplom.date.DateValues$Values#757fc606">5</option>
<option value="dyplom.dyplom.date.DateValues$Values#17a1f02e">6</option>
<option value="dyplom.dyplom.date.DateValues$Values#89f6821">7</option>
<option value="dyplom.dyplom.date.DateValues$Values#196d52f3">8</option>
<option value="dyplom.dyplom.date.DateValues$Values#5860dc8f">9</option>
<option value="dyplom.dyplom.date.DateValues$Values#3f305d9d">10</option>
<option value="dyplom.dyplom.date.DateValues$Values#520ed4">11</option>
<option value="dyplom.dyplom.date.DateValues$Values#b4b8076">12</option>
</select>
</h2>
Problem solved!
I'm so ashamed of the mistake I made!
Take a look at the constructor of Values:
public Values(String valueLabel, String valueValue){
this.valueLabel = valueValue;
this.valueLabel = valueValue;
}
As you can see I've been setting up twice valueLabel with wrong variable and moreover I didn't set valueValue at all!
Now as I corrected constructor:
public Values(String valueLabel, String valueValue){
this.valueLabel = valueLabel;
this.valueValue = valueValue;
}
everything is alright :)
Sorry for the mess!

how to delete previusly selected file based on index value in mvc3?

Hi all i am working on mvc3
here i need to delete a previously uploaded file from the sessions data
anh i am displaying the file before inserting into data base so i am displaying the data in sessions now i need to delete the previously selected file plz help to how to get the selected file index value to delete the file from the sessions
For example here check this post it is in c# but i need this is in mvc3 please help me to do this work plz help me anyone
here my models are
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BugTracker.Models
{
public class BugModel
{
public BugModel()
{
if (ListFile == null)
ListFile = new List<BugAttachment>();
}
public List<BugAttachment> ListFile { get; set; }
public string ErrorMessage { get; set; }
}
public class BugAttachment
{
public string FileName { get; set; }
public int BugAttachmentID { get; set; }
public string AttachmentName { get; set; }
public int BugID { get; set; }
public string AttachmentUrl { get; set; }
public string AttachedBy { get; set; }
}
}
here my controllers
public ActionResult UploadFile(string AttachmentName, BugModel model)
BugModel bug = null;
if (Session["CaptureData"] == null)
{
bug = model;
}
else
{
bug = (BugModel)Session["CaptureData"];
}
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file1 = Request.Files[inputTagName];
if (file1.ContentLength > 0)
{
BugAttachment attachment = new BugAttachment();
var allowedExtensions = new[] { ".doc", ".xlsx", ".txt", ".jpeg", ".docx" };
var extension = Path.GetExtension(file1.FileName);
if (!allowedExtensions.Contains(extension))
{
model.ErrorMessage = "{ .doc, .xlsx, .txt, .jpeg }, files are allowed.... ";
}
else
{
string filename = Guid.NewGuid() + Path.GetFileName(file1.FileName);
string path = "/Content/UploadedFiles/" + filename;
string savedFileName = Path.Combine(Server.MapPath("~" + path));
file1.SaveAs(savedFileName);
attachment.FileName = "~" + path.ToString();
attachment.AttachmentName = AttachmentName;
attachment.AttachmentUrl = attachment.FileName;
bug.ListFile.Add(attachment);
model = bug;
}
Session["CaptureData"] = model;
}
}
ModelState.Clear();
return View("LoadBug", bug);
}
and here my view page
<div class="UploadMain">
<%:Html.Label("Attachment Name:") %>
<%:Html.TextBoxFor(model=>model.AttachmentName) %>
<span>
<%:Html.Label("Upload Files") %></span>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" id="Upload" class="style-name cancel" />
<%--onclick="window.location.href='<%= Url.Action("UploadFile", "Bug") %>';"--%>
<table align="center" class="gridtable" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>
Attachment Name
</th>
<th>
Attachment Url
</th>
<th>
Action
</th>
</tr>
<% if (Model != null && Model.ListFile != null)
{ %>
<% foreach (var Emp in Model.ListFile)
{ %>
<tr class="Data">
<td >
<%:Emp.AttachmentName %>
</td>
<td >
<%: Emp.FileName %>
</td>
<td>
<%-- <%= Html.ActionLink("Delete", "Delete")%>--%>
<%:Html.ActionLink("Delete", "Delete", new { #FileName = Emp.FileName })%>
</td>
</tr>
<% } %>
<% } %>
</table>
</div>
For example here check this post it is in c# but i need this is in mvc3 please help me to do this work plz help me anyone
thanks in advance
To delete a file you uploaded all you need is its filepath, and use File.Delete("filepath");
To know which file to delete your Delete action should take an id:
Delete(int id)
Then in your action link pass the BugAttachmentID: (using route values/parameters)
<%:Html.ActionLink("Delete", "Delete", new { #FileName = Emp.FileName }, new { id = Emp.BugAttachmentID })%>
Then in your delete method you use the ID to find the file in the FileList you want to delete. And then call File.Delete using the attachment url.
I hope this helps.

Resources