I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn't recognize the checkbox data
I'm not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !
ViewModel:
public List<cDay> _cDays = new List <cDay>();
public List<cDay> cDays
{
get {return _cDays;}
set {_cDays = value;}
}
public class cDay
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
}
CSHtml file:
#Html.Label("M")
#Html.CheckBox("Monday", false, new { #class = "availability" })
// this is basically the same code for Tuesday-Friday as well.
'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
if(ModelState.IsValid)
//
}
Consider to use the following data model:
public class DaysViewModel
{
public List<CDay> Days { get; set; } = new List<CDay>();
}
public class CDay
{
public CDay()
{
Name = string.Empty;
Selected = false;
}
public CDay(string name)
{
Name = name;
Selected = false;
}
[Required]
public string Name { get; set; }
[Required]
public bool Selected { get; set; }
}
Then you can use the default ASP.NET MVC data binding without a JS support:
#model Models.DaysViewModel
#using (Html.BeginForm("Edit", "Home"))
{
#Html.AntiForgeryToken()
for(int i=0; i < Model.Days.Count; i++)
{
<div class="form-group row">
#Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)
#Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
<span>#Model.Days[i].Name </span>
</div>
}
<input type="submit" value="Save" />
}
And on the server side:
public ActionResult Edit()
{
var model = new DaysViewModel();
model.Days.AddRange( new List<CDay> {
new CDay("Monday"),
new CDay("Tuesday"),
new CDay("Wednesday"),
new CDay("Thursday"),
new CDay("Friday")
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<CDay> days)
{
if(ModelState.IsValid)
{
// ... you_code here
}
var model = new DaysViewModel() { Days = days };
return View(model);
}
Test screen shots
The view:
On the controller side:
You can do it using jQuery
Add a button bellow your checkboxes
<input type="button" value="Your_Value" class="btn btn-default" />
When click on a button create a post request and sends checked status via querystring
$(document).ready(function () {
$("input[type=button]").click(function () {
var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
$.ajax({
type: "Post",
url: "/Home/Edit?" + queryString,
success: function (data) {
},
error: function (data) {
}
});
});
});
And inside controller create Edit Post Method like this
[HttpPost]
public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
{
...
}
Related
I'm using Facebook Graph JSON responses in my code to deserialize the JSON string.
I created the class as follow.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="fb-root"></div>
Login with Facebook
<br /> <br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '<%= ecommerce.fblogin.FaceBookAppKey %>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true // enable OAuth 2.0
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
function loginByFacebook() {
FB.login(function (response) {
if (response.authResponse) {
FacebookLoggedIn(response);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
function FacebookLoggedIn(response) {
var loc = '/fblogin.aspx';
if (loc.indexOf('?') > -1)
window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
else
window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
}
</script>
</form>
namespace ecommerce
{
public partial class fblogin : System.Web.UI.Page
{
public const string FaceBookAppKey = "xxxxxxxxxx";
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["access_token"])) return; //ERROR! No token returned from Facebook!!
//let's send an http-request to facebook using the token
string json = GetFacebookUserJSON(Request.QueryString["access_token"]);
//and Deserialize the JSON response
JavaScriptSerializer js = new JavaScriptSerializer();
FacebookUser oUser = js.Deserialize<FacebookUser>(json);
if (oUser != null)
{
Response.Write("Welcome, " + oUser.name);
Response.Write("<br />id, " + oUser.id);
Response.Write("<br />email, " + oUser.email);
Response.Write("<br />first_name, " + oUser.first_name);
Response.Write("<br />last_name, " + oUser.last_name);
Response.Write("<br />gender, " + oUser.gender);
Response.Write("<br />link, " + oUser.link);
Response.Write("<br />updated_time, " + oUser.updated_time);
Response.Write("<br />birthday, " + oUser.birthday);
Response.Write("<br />locale, " + oUser.locale);
Response.Write("<br />picture, " + oUser.picture);
if (oUser.location != null)
{
Response.Write("<br />locationid, " + oUser.location.id);
Response.Write("<br />location_name, " + oUser.location.name);
}
}
}
private static string GetFacebookUserJSON(string access_token)
{
string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link", access_token);
WebClient wc = new WebClient();
Stream data = wc.OpenRead(url);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
data.Close();
reader.Close();
return s;
}
public class FacebookUser
{
public long id { get; set; }
public string email { get; set; }
public string name
{ get; set; }
public string first_name
{ get; set; }
public string last_name
{ get; set; }
public string gender
{ get; set; }
public string link
{ get; set; }
public DateTime updated_time
{ get; set; }
public DateTime birthday
{ get; set; }
public string locale
{ get; set; }
public string picture
{ get; set; }
public FacebookLocation location
{ get; set; }
}
public class FacebookLocation
{
public string id
{ get; set; }
public string name
{ get; set; }
}
static int a = 0;
protected void Button1_Click(object sender, EventArgs e)
{
a++;
Label1.Text = Convert.ToString(a);
}
}
}
After added update panel my Facebook login function not working after the link is clicked.
I added AJAX page request manager. The post Back settings function it not work as what I expected.
After I remove added update panel works is working as I expect.
/** This is what I try, but not work */
function loginByFacebook() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm._postBackSettings(function (sender, e) {
if (sender.loginByFacebook.panelsToUpdate != null) {
loginByFacebook();
}
});
};
}
*/
Below is the screenshot issues i'm stuck.
Update panel events are rendered partially hence the events will looses.
After Login or Register Button is click. The Facebook login will not work as expected. The dialog box will not close automatically.
Hope one kindly can help me, it may be a simple question but frustrated me as there is no fix for it,
I want to pass value from a hidden field to controller via model binding,
no matter what approach I use, just passing the value from view to controller via model can work for me,
this is my slider range
<label for="amount">دامنه قیمت:</label>
<div id="connect" class="noUi-target noUi-ltr noUi-horizontal noUi-background">
</div>
this is the hidden field,
<input type="hidden" name="MinPrice" value="#Model.MinPrice" id="MinPrice" />
<input type="hidden" name="MaxPrice" value="#Model.MaxPrice" id="MaxPrice" />
< script >
var connectSlider = document.getElementById('connect');
noUiSlider.create(connectSlider, {
start: [40000, 800000],
connect: true,
range: {
'min': 0,
'max': 2000000
}
}); < /script>
<script>
var connectBar = document.createElement('div'),
connectBase = connectSlider.querySelector('.noUi-base');
/ / Give the bar a class
for styling and add it to the slider.
connectBar.className += 'connect';
connectBase.appendChild(connectBar);
connectSlider.noUiSlider.on('update', function(values, handle, a, b, handlePositions) {
var offset = handlePositions[handle];
// Right offset is 100% - left offset
if (handle === 1) {
offset = 100 - offset;
}
// Pick left for the first handle, right for the second.
connectBar.style[handle ? 'right' : 'left'] = offset + '%';
}); < /script>
<script>
var valueInput = document.getElementById('MinPrice'),
valueSpan = document.getElementById('MaxPrice');
/ / When the slider value changes, update the input and span
connectSlider.noUiSlider.on('update', function(values, handle) {
if (handle) {
valueInput.value = values[handle];
} else {
valueSpan.innerHTML = values[handle];
}
});
// When the input changes, set the slider value
valueInput.addEventListener('change', function() {
connectSlider.noUiSlider.set([null, this.value]);
});
< /script>
this is my JS that fill the hidden field, these two fields are filled correctly, but dont send data to controller via model,
thank you all pal,
Updated
this is my model:
public class SearchModel
{
public string Devision { get; set; }
public string Gender { get; set; }
public int? MinPrice { get; set; }
public int? MaxPrice { get; set; }
public string Brand { get; set; }
public string Sport { get; set; }
public string Size { get; set; }
public string ProductGroup { get; set; }
public List<tblSiteItem> Result { get; set; }
public List<tblSiteItem> Sales { get; set; }
public List<string> Devisions { get; set; }
public List<string> Genders { get; set; }
public List<string> Brands { get; set; }
public List<string> Sports { get; set; }
public List<string> Sizes { get; set; }
public List<string> ProductGroups { get; set; }
public List<tblSiteCart> CartItems { get; set; }
public int PageNo { get; set; }
public int Barcode { get; set; }
}
As I said the value is filled correctly so I do not need code to make it corrected, Just not bind the hdnValue to the field in my model.
I mean MinPrice and MaxPrice.
Edited
I am not allowed to upload images sadly, If I were everything was pretty obvious to look at,
any way, I explain the detail:
when I change the slideBar, my JS fires and values change,
when I click the search button all the fields in my model is field except for these two field , I mean MinPrice and MaxPrice
result shows an empty page , again my Js keep fired then come back to the default values,
in the last try I changed the hidden field to type="text"
and saw that when I change the slidebar the value is in my text box but not binded to my view model when touch search button.
I am sure there is something wrong with my viewmodel, but How I can understand what is incorrect :( please kindly look at my code
The names of your inputs are incorrect. You should remove the Model. part from it. If you used HtmlHelper.HiddenFor, you'd get the following:
<input type="hidden" name="MaxPrice" value="#Model.MaxPrice" id="MaxPrice" />
This way, the inputs will get submitted to your model correctly.
Have a look at this answer.
Use this code for get the value:
var userRole = "";
userRole = $("#hdnVal").val();
alert(userRole);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hdnVal" value="#Model.MinPrice" />
Follow this.
On .cshtml Page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hdnVal" value="#Model.MinPrice" />
<input type="button" name="Submit" value="Submit" id="btnSubmit" class="btn btn-primary" />
Js
var userRole = "";
userRole = $("#hdnVal").val();
alert(userRole);
$('#btnSubmit').click(function() {
var formData = new FormData();
formData.append("userRole ", userRole);
$.ajax({
type: "POST",
url: "/Controller/YourAction/",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(result) {
if (result.Message == "success") {
alert("Success");
}
}
});
}
C# Code
public JsonResult YourAction()
{
string Role = Request.Form["userRole "];
//You can get the value of role
}
I had the same problem and after several test I found the solution sending values via ajax but building the data for the request in a string JSON format, where the hidden fields, are written without single quotes and the other fields with single quotes. Below is shown the example. I hope that this variant help you.
JavaScript code to send data to controller
$("#saveSearchModel").on("click", function (e) {
e.preventDefault();
// Variables for fields values
var devision = $("#Devision").val();
var gender = $("#Gender").val();
var minPrice = $("#MinPrice").val();
var maxPrice = $("#MaxPrice").val();
var brand = $("#Brand").val();
/*
Get the other fields...
*/
// Data for pass to controller via ajax
var data1 = "{'Devision':'" + devision + "','Gender':'" + gender + "',MinPrice:" + minPrice + ",MaxPrice:" + maxPrice + ",'Brand':'" + brand + /*Add the other fields...*/ + "'}";
$.ajax({
url: '/Controller/Action1',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: data1,
success: function (result) {
// Do something
}
});
});
Code in controller to receive data
[HttpPost]
public void Action1(SearchModel model)
{
// Gets the values of model
string devision = model.Devision;
string gender = model.Gender;
int? minPrice = model.MinPrice;
int? maxPrice = model.MaxPrice;
string brand = model.Brand;
/*
Gets the others values of model...
*/
}
I am working with spring batch , I have configured my job to be executed by clicking on a button (spring MVC).
all information about my job are in BATCH_JOB_EXECUTION in the database.
I want to have this scenario:
-when I load the page , the table contains all the records existing in the database
-when I click on the button to execute my job, the last record added in the database is added in the front end of my table.
This is what I have done But still not working!
Here is the content of BATCH_JOB_EXECUTION.java file :
public class BATCH_JOB_EXECUTION {
private int JOB_EXECUTION_ID ;
private int VERSION;
private int JOB_INSTANCE_ID;
private Time CREATE_TIME ;
private Time START_TIME;
private Time END_TIME;
private String STATUS;
private String EXIT_CODE;
private String EXIT_MESSAGE;
private Time LAST_UPDATED;
public BATCH_JOB_EXECUTION(){
}
public int getJOB_EXECUTION_ID() {
return JOB_EXECUTION_ID;
}
public void setJOB_EXECUTION_ID(int jOB_EXECUTION_ID) {
JOB_EXECUTION_ID = jOB_EXECUTION_ID;
}
public int getVERSION() {
return VERSION;
}
public void setVERSION(int vERSION) {
VERSION = vERSION;
}
public int getJOB_INSTANCE_ID() {
return JOB_INSTANCE_ID;
}
public void setJOB_INSTANCE_ID(int jOB_INSTANCE_ID) {
JOB_INSTANCE_ID = jOB_INSTANCE_ID;
}
public Time getCREATE_TIME() {
return CREATE_TIME;
}
public void setCREATE_TIME(Time cREATE_TIME) {
CREATE_TIME = cREATE_TIME;
}
public Time getSTART_TIME() {
return START_TIME;
}
public void setSTART_TIME(Time sTART_TIME) {
START_TIME = sTART_TIME;
}
public Time getEND_TIME() {
return END_TIME;
}
public void setEND_TIME(Time eND_TIME) {
END_TIME = eND_TIME;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
public String getEXIT_CODE() {
return EXIT_CODE;
}
public void setEXIT_CODE(String eXIT_CODE) {
EXIT_CODE = eXIT_CODE;
}
public String getEXIT_MESSAGE() {
return EXIT_MESSAGE;
}
public void setEXIT_MESSAGE(String eXIT_MESSAGE) {
EXIT_MESSAGE = eXIT_MESSAGE;
}
public Time getLAST_UPDATED() {
return LAST_UPDATED;
}
public void setLAST_UPDATED(Time lAST_UPDATED) {
LAST_UPDATED = lAST_UPDATED;
}
}
and here is my view :
<div>
<table id="contactTableResponse" class="table tr">
<thead>
<tr>
<th>JOB_INSTANCE_ID</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>EXIT_CODE</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Spring-Ajax</th>
<td colspan="4">JQuery Ajax</td>
</tr>
</tfoot>
<tbody>
<c:forEach items="${jobs}" var="BATCH_JOB_EXECUTION">
<tr>
<td>${BATCH_JOB_EXECUTION.JOB_INSTANCE_ID}</td>
<td>${BATCH_JOB_EXECUTION.START_TIME}</td>
<td>${BATCH_JOB_EXECUTION.END_TIME}</td>
<td>${BATCH_JOB_EXECUTION.EXIT_CODE}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
The ajax call:
$('#JobBtn').click( function() {
$('#JobBtn').click( function() {
alert('in submit function');
$.ajax({
type: 'GET',
url: 'load',
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
Updated
this is my controller:
public class AjacController {
#Inject
#Named(value = "dataSource")
private DataSource dataSource1;
#RequestMapping(value="/load" )
public ModelAndView connect(){
ModelAndView model = new ModelAndView("");
BATCH_JOB_EXECUTION batch=null;
List<BATCH_JOB_EXECUTION> list =null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
String select= "select JOB_INSTANCE_ID, START_TIME,END_TIME,EXIT_CODE from BATCH_JOB_EXECUTION";
try {
connection = dataSource1.getConnection();
preparedStatement = connection.prepareStatement(select);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
batch.setJOB_EXECUTION_ID(resultSet.getInt("JOB_INSTANCE_ID")) ;
batch.setSTART_TIME(resultSet.getTime("START_TIME")) ;
batch.setEND_TIME(resultSet.getTime("END_TIME")) ;
batch.setEXIT_CODE(resultSet.getString("EXIT_CODE")) ;
list.add(batch);
model.addObject("listJobs", list);
}
return model ;
}
but data is not displayed in my table!
Any help will be appreciated.
I have a table in a page. I want to update / reload the table continuously on a button click for every 5 seconds.
The table gets the values from the query running in the model and I don't want duplicate values to be put in the table again.
I also want to stop the reloading of the table on when I click on a another button which is the stop button.
How can I do it? Thanks!
When you click on first button set interval function, which will execute your updating script. And click on other button will clear this interval.
// Click on first button
var flag = setInterval(func, 5000);
// Click on second button
clearInterval(flag);
where func is your updating function
Try that if possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using bhanu1.Models;
namespace bhanu1.Controllers
{
public class ranuController : Controller
{
//
// GET: /ranu/
private personEntities1 per = new personEntities1();
public ActionResult Index()
{
return View(per.sandeep1.ToList());
}
//
// GET: /ranu/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /ranu/Create
public ActionResult Create()
{
return View();
}
//
// POST: /ranu/Create
[HttpPost]
public ActionResult Create([Bind(Exclude = "Id")]sandeep1 san)
{
try
{
// TODO: Add insert logic here
per.AddTosandeep1(san);
per.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ranu/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /ranu/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ranu/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /ranu/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
I have a little (i hope) problem trying to use Doubleselect element from Struts2 jQuery plugin. I have followed the sample without problems, and the behaviour is as expected when I add a new record (add new record to database), but when i try to edit an existing one the second select does not load the stored value for the record being edited.
Any help?
Code and configuration follows:
JSP code
<s:form id="ingresoForm" action="saveIngreso" method="post" validate="true" cssClass="well form-horizontal">
<s:hidden key="ingreso.id"/>
<s:hidden key="cliente" id="cliente"/>
<div class="type-text">
<label for="cliente">Cliente: </label>
<s:url var="remoteurl" action="ajax/clienteProyectoSelectSource"/>
<sj:select
href="%{remoteurl}"
id="clienteSelect"
onChangeTopics="reloadsecondlist"
name="ingreso.cliente.id"
list="clientes"
listKey="id"
listValue="nombre"
emptyOption="false"
headerKey="-10"
headerValue="Por favor seleccione un cliente"/>
</div>
<div class="type-text">
<label for="Proyecto">Proyecto: </label>
<sj:select
href="%{remoteurl}"
id="proyectoSelect"
formIds="ingresoForm"
reloadTopics="reloadsecondlist"
name="ingreso.proyecto.id"
list="proyectos"
listKey="id"
listValue="nombre"
emptyOption="false"
/>
</div>
Action Code
public class ClienteProyectoSelectSourceAjaxAction extends BaseAction {
private List<Cliente> clientes;
private List<Proyecto> proyectos;
private String cliente;
private GenericManager<Cliente, Long> clienteManager;
#Override
public String execute() {
clientes = clienteManager.getAll();
if (cliente != null && cliente.length() > 0 && !cliente.equals("-10")) {
proyectos = clienteManager.get(new Long(cliente)).getProyectos();
}
return Action.SUCCESS;
}
Action Declaration
<package name="example" extends="json-default" namespace="/ajax">
<action name="clienteProyectoSelectSource" class="com.queres.smtm.webapp.action.ajax.ClienteProyectoSelectSourceAjaxAction">
<result type="json"/>
</action>
</package>
Ingreso entity (model)
#Entity
#Table(name = "ingreso")
public class Ingreso extends BaseObject {
// Campos comunes
private Long id;
private TipoIngreso tipo;
private String observaciones;
private BigDecimal importe;
private BigDecimal tipoIVA;
private Date fechaPrevistaCobro;
private Date fechaEfectivaCobro;
// Campos para facturas
private String numeroFactura;
private Cliente cliente;
private Proyecto proyecto;
private TipoServicio servicio;
private Date fechaEmision;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Enumerated(EnumType.STRING)
public TipoIngreso getTipo() {
return tipo;
}
public void setTipo(TipoIngreso tipo) {
this.tipo = tipo;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public BigDecimal getImporte() {
return importe;
}
public void setImporte(BigDecimal importe) {
this.importe = importe;
}
public BigDecimal getTipoIVA() {
return tipoIVA;
}
public void setTipoIVA(BigDecimal tipoIVA) {
this.tipoIVA = tipoIVA;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaPrevistaCobro() {
return fechaPrevistaCobro;
}
public void setFechaPrevistaCobro(Date fechaPrevistaCobro) {
this.fechaPrevistaCobro = fechaPrevistaCobro;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaEfectivaCobro() {
return fechaEfectivaCobro;
}
public void setFechaEfectivaCobro(Date fechaEfectivaCobro) {
this.fechaEfectivaCobro = fechaEfectivaCobro;
}
public String getNumeroFactura() {
return numeroFactura;
}
public void setNumeroFactura(String numeroFactura) {
this.numeroFactura = numeroFactura;
}
#ManyToOne
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
#ManyToOne
public Proyecto getProyecto() {
return proyecto;
}
public void setProyecto(Proyecto proyecto) {
this.proyecto = proyecto;
}
#Enumerated(EnumType.STRING)
public TipoServicio getServicio() {
return servicio;
}
public void setServicio(TipoServicio servicio) {
this.servicio = servicio;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaEmision() {
return fechaEmision;
}
public void setFechaEmision(Date fechaEmision) {
this.fechaEmision = fechaEmision;
}
#Override
public int hashCode() {
int hash = 3;
hash = 43 * hash + (this.numeroFactura != null ? this.numeroFactura.hashCode() : 0);
hash = 43 * hash + (this.fechaEmision != null ? this.fechaEmision.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Ingreso other = (Ingreso) obj;
if ((this.numeroFactura == null) ? (other.numeroFactura != null) : !this.numeroFactura.equals(other.numeroFactura)) {
return false;
}
if (this.fechaEmision != other.fechaEmision && (this.fechaEmision == null || !this.fechaEmision.equals(other.fechaEmision))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Ingreso{" + "id=" + id + ", tipo=" + tipo + ", observaciones=" + observaciones + ", importe=" + importe + ", tipoIVA=" + tipoIVA + ", fechaPrevistaCobro=" + fechaPrevistaCobro + ", fechaEfectivaCobro=" + fechaEfectivaCobro + ", numeroFactura=" + numeroFactura + ", cliente=" + cliente + ", proyecto=" + proyecto + ", servicio=" + servicio + ", fechaEmision=" + fechaEmision + '}';
}
}
Thx in advance
Problem solved. It seems that jquery-plugin work perfectly, as usual the error was between the keyboard and the chair...
I forgot to load the data list for the second select, so jquery was unable to select the aproppiate value.
So, the solution was to ensure that the second list (proyectos) was loaded when the user edits an element.
I add a flag (cliente) as a hidden element on JSP and preloaded it from the main action, so I can check from the Ajax Action if it is necessary to populate the second list.
Ingreso Action (main action for the view)
public class IngresoAction extends BaseAction implements Preparable {
private String cliente;
public String edit() {
if (id != null) {
ingreso = ingresoManager.get(id);
cliente = Long.toString(ingreso.getCliente().getId());
} else {
ingreso = new Ingreso();
}
return SUCCESS;
}
public String getCliente() {
return cliente;
}
public void setCliente(String cliente) {
this.cliente = cliente;
}
<...>