How to set value to a hidden property with a button? - javascript

I have the following files:
view.jsp
<# page import=...
<bean:define id="mForm" name="myForm" type="MyForm"/>
<html:form action="MyFoo" method="post" styleId="myForm" enctype="multipart/form-data">
<html:hidden property="boo"/>
<input type="button" value="Press me" onclick="javascript:changeBoo()"/>
</html:form>
MyForm.java
class MyForm {
private boolean boo;
public void setBoo(boolean boo){
this.boo = boo;
}
public boolean getBoo(){
return this.boo;
}
}
MyFooAction.java
public class MyFooAction extends BaseAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward aForward = null;
String forward = "success";
try {
MyForm myForm = (MyForm) form;
String boo = (String)request.getParameter("boo");
if(boo.equals("true")){
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>DONE");
}
else {
//some code here
}
aForward = mapping.findForward(forward);
}
catch (Exception e) {
throw new Exception();
}
return aForward;
}
}
The question is how to implement changeBoo() in Javascript in order to change the value of boo and to invoke MyFooAction with correct value of boo?

First, change your button to type="submit". That will take care of submitting the form for you. Notice how changeBoo() now returns a value for your onclick attribute. This will submit the form if your function returns true.
Also, you'll need to add an id attribute to your hidden field so that you can easily get a reference to it from javascript:
<html:hidden property="boo" id="booId" />
<input type="submit" value="Press me" onclick="return changeBoo();"/>
Then it's just a matter of creating the javascript function:
function changeBoo(){
var boo = document.getElementById('booId');
boo.value = 'The new value';
return true;
}

PS On your <html:form>...</html:form>, make sure you have a way to submit a form. This is usually done by adding <html:submit>.
Now, to come back to your question, your Javascript function will be like this (assuming that your ActionForm name specified on struts-config.xml is "myForm").
fumction changeBoo() {
var boo = document.myForm.boo;
if ("true" == boo.value.toLowerCase() || "yes" == boo.value.toLowerCase() || "1" == boo.value.toLowerCase()) {
boo.value = "false";
} else {
boo.value = "true";
}
}
Bear in mind that Struts converts boolean values to "true" or "false", "yes" or "no", "0" or "1".

Related

Validation message is not displaying for custom attribute in .Net Core

I am creating custom attribut for validation to override RegularExpressionAttribute in .Net Core, and Implemented IClientModelValidator for client side validation. validation is apply on field but didn't display Error message for it. ModelState.IsValid is also giving Invalid that field but validation message is not displaying.
ViewModel
[Required]
[Display(Name = "First Name")]
[RestrictSplCharacters]
public string FirstName { get; set; }
Override Attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class RestrictSplCharactersAttribute : RegularExpressionAttribute, IClientModelValidator
{
private string errorMessage= "Special characters or blank space is not allowed in {0}";
public RestrictSplCharactersAttribute()
: base(#"[_A-z0-9]*((-|\s)*[_A-z0-9])*$")
{
this.ErrorMessage = this.errorMessage;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-restrictSplCharacters", errorMessage);
}
private bool MergeAttribute(
IDictionary<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
In Html Control is like
<div class="oneditshow">
<input autocomplete="off" class="k-textbox valid k-valid" data-val="true" data-val-required="The First Name field is required." data-val-restrictSplCharacters="Special characters or blank space is not allowed in First Name" id="FirstName" name="FirstName" placeholder="First Name" required="required" style="width: 100%" value="" aria-required="true" aria-describedby="FirstName-error">
<span class="text-danger field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true" style="display: none;"></span>
</div>
Javascript function
<script>
var $jQval = $.validator;
$jQval.addMethod("restrictSplCharacters",
function (value, element, parameters) {
var regExp = "/[_A-z0-9]*((-|\s)*[_A-z0-9])*$/";
if (value.match(regExp)) {
return true;
} else {
return false;
}
});
var adapters = $jQval.unobtrusive.adapters;
adapters.addBool("restrictSplCharacters");
</script>
Thank you, Client Side validation is not fired because it's kendo UI.
I replace my JavaScript with Below javascript for kendo custom validation Rule.
//register custom validation rules
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: { // custom rules
restrictSpecialCharacters: function (input, params) {
//check for the rule attribute
if (input.filter("[data-val-restrictSpecialCharacters]").length && input.val()) {
return /[_A-z0-9]*((-|\s)*[_A-z0-9])*$/.test(input.val());
}
return true;
}
},
messages: { //custom rules messages
restrictSpecialCharacters: function (input) {
// return the message text
return input.attr("data-val-restrictSpecialCharacters");
}
}
});
})(jQuery, kendo);
Try with adding following code after public void AddValidation in RestrictSpecialCharactersAttribute.
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mvr = new ModelClientValidationRule();
mvr.ErrorMessage = this.eRRORMESSAGE;
mvr.ValidationType = "restrictSpecialCharacters";
return new[] { mvr };
}
You can find more details here.

Values are sent as null when using js prompt

I want to save the entered value of the database. However, values are sent as null.
I'm glad if I encode additional help.
HomeConteller.cs
[HttpPost]
public void GaleriOlustur(string Adi)
{
GaleriTanim As = new GaleriTanim() { Adi = Adi };
db.GaleriTanims.Add(As);
db.SaveChanges();
islemler islem = new islemler { islemler1 = "Galeri Oluşturuldu", kayitTarihi = DateTime.Now };
db.islemlers.Add(islem);
db.SaveChanges();
RedirectToAction("GaleriYonet", "Home");
}
GaleriYonet.cshtml
#using (Html.BeginForm("GaleriOlustur", "Home",FormMethod.Post,new {Adi="Adi"}))
{
<input type="submit" onclick="GaleriOlustur()" name="Adi" value="Galeri Oluştur"/>
}
GaleriYonet.cshtml "Javascript"
<script type="text/javascript">
function GaleriOlustur() {
var Adi = prompt("Galeri İsmi Giriniz");
if (Adi != null) {
return Adi;
} else {
alert("Bir İsim Girmelisiniz.");
return false;
}
};
Your client side function should either return true or false. Not the value user entered to the prompt.
I also suggest you keep an input variable value (hidden type) in your form with name matching to your action method parameter name. In your javascript method, when user enter a vliad value, you can update this form control value to that.
Also, you need to do return GaleriOlustur() on the onclick event
#using (Html.BeginForm("GaleriOlustur", "Home", FormMethod.Post, new { Adi = "Adi" }))
{
<input type="hidden" name="Adi" />
<input type="submit" onclick="return GaleriOlustur()" value="Galeri Oluştur" />
}
and in js method, set the input field value to the value user entered.
function GaleriOlustur() {
var adi = prompt("Galeri İsmi Giriniz");
if (adi !=="") {
$("input[name='Adi']").val(adi);
return true;
} else {
alert("Bir İsim Girmelisiniz.");
return false;
}
};

Triggering a ActionResult method off of a checkbox toggle

I'm a semi-competent Winforms/WPF/MVVM/c#/vb.Net dev, attempting to teach myself ASP.Net with MVC and i'm a little confused as to how you "raise events" (i know MVC doesn't do events but that's what i'm equating it to) off of anything that's not a form's submit button. I have a View, Controller and a Model for a simple to-do list style application and i'm wondering how i can trigger some code in the controller off of the toggling of the check box. This is my code:
View (Views/ToDo/Index.cshtml):
#{
ViewBag.Title = "Index";
}
#model List<ToDo.Models.ToDoListItem>
<h2>To Do List</h2>
<form action="/ToDo/Create" method="post">
<div>
<input name="ToDoItem" />
<input type="submit" value="Add Task" />
</div>
</form>
<div>
<ul>
#if (Model != null)
{
foreach (var item in Model)
{
<li>
<form action="/ToDo/Delete/#item.ItemId " method="post">
<input type="checkbox" checked="#item.isChecked" />
#if (item.isCompleted)
{
<label style="text-decoration-line:line-through">#item.ItemText</label>
}
else
{
<label>#item.ItemText</label>
}
<input type="submit" value="Delete" />
</form>
</li>
}
}
</ul>
</div>
Controller (Controllers/ToDoController.cs):
namespace ToDo.Controllers
{
public class ToDoController : Controller
{
// GET: ToDo
public ActionResult Index()
{
return View(Models.ToDoListItem.GetAll());
}
[HttpPost]
public ActionResult Create(string toDoItem)
{
Models.ToDoListItem.Create(toDoItem, Models.ToDoListItem.GetNextID());
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Delete(string id)
{
int itemIdentifier = Convert.ToInt32(id);
Models.ToDoListItem.Delete(itemIdentifier);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult CheckBoxToggle(string id)
{
int itemIdentifier = Convert.ToInt32(id);
Models.ToDoListItem.CompleteToggeled(itemIdentifier);
return RedirectToAction("Index");
}
}
}
Model (Models/ToDiListItem.cs):
namespace ToDo.Models
{
public class ToDoListItem
{
#region Fields
private int _itemId;
private string _itemText;
private bool _isCompleted;
#endregion
#region Events
#endregion
#region Properties
public int ItemId
{
get
{
return _itemId;
}
set
{
_itemId = value;
}
}
public string ItemText
{
get
{
return _itemText;
}
set
{
_itemText = value;
}
}
public bool isCompleted
{
get
{
return _isCompleted;
}
set
{
_isCompleted = value;
}
}
public string isChecked
{
get
{
if (isCompleted)
return "checked";
else
return string.Empty;
}
}
#endregion
#region Public Methods
public static void Create(string toDoItem, int itemId)
{
var item = new ToDoListItem();
item.ItemText = toDoItem;
item.ItemId = itemId;
GlobalVariables.Tasks.Add(item);
}
public static void Delete(int id)
{
foreach (ToDoListItem item in GlobalVariables.Tasks)
{
if (item.ItemId == id)
{
GlobalVariables.Tasks.Remove(item);
break;
}
}
}
public static void CompleteToggeled(int id)
{
foreach (ToDoListItem item in GlobalVariables.Tasks)
{
if (item.ItemId == id)
{
item.isCompleted = !item.isCompleted;
}
}
}
public static List<ToDoListItem> GetAll()
{
return GlobalVariables.Tasks;
}
public static int GetNextID()
{
return ++GlobalVariables.CurrentID;
}
#endregion
}
}
So, what i am looking to do, is to be able to toggle the "checked" state one of the checkboxes on the form and call the "CheckBoxToggle" method in my controller, passing in the ID of the item (similarly to how i did it on the delete button). I've seen something to do with Javascript (which i know nothing about) being mentioned, but i have no real idea what i am doing with it and nothing i've seen so far explains it particularly clearly.
If anyone knows the best way for me to go about this, some assistance would be much appreciated.
You can listen to the change event on the checkbox and post the form which includes an input form element with same name as your HttpPost action method parameter.
Update your markup so that it will have a css class which we will use as our jQuery selector for wiring up the event listener for the checbox toggle event. Also you can keep the Id of item in an input hidden field with same name as your parameter (Id)
#using (Html.BeginForm("CheckBoxToggle", "Todo"))
{
<input type="checkbox" class="myChk" name="isChecked" checked="checked"/>
<input type="hidden" name="id" value="#item.Id" />
}
Now basically you need to listen to the click event on the check box.
$(function(){
$(".myChk").click(function() {
$(this).closest("form").submit();
});
});
Assuming you have jQuery library loaded to your page.
I also see you are receiving the parameter value in string and converting it back to int. Why not use the int type param ? You may also add one more parameterr named isChecked to know whether user checked the checkbox or unchecked. When it is checked the parameter value will be not null
[HttpPost]
public ActionResult CheckBoxToggle(int id,string isChecked)
{
Models.ToDoListItem.CompleteToggeled(id);
return RedirectToAction("Index");
}

Disable Submit Button during Postback

I'm trying to disable the button during form submission but not able to do so. Here is the javascript code
<script type="text/javascript">
function Validate(b)
{
function stuff()
{
var temp = document.getElementById("<%=txt_stuff.ClientID %>").value;
var val = /^[a-zA-Z0-9 ]+$/
if(temp=="")
{
alert("Please Enter Stuff");
return false;
}
else if(val.test(temp))
{
return true;
}
else
{
alert("Name accepts only spaces and charcters");
return false;
}
}
function price()
{
var temp2 = document.getElementById("<%=txt_price.ClientID %>").value;
var val2 = /^[0-9 ]+$/
if(temp2=="")
{
alert("Please Enter Price");
return false;
}
else if(val2.test(temp2))
{
return true;
}
else
{
alert("Price accepts only Number");
return false;
}
}
if(stuff() && price())
{
b.disabled = true;
b.value = 'Submitting...';
return true;
}
else
{
return false;
}
}
</script>
Here is the button code
<asp:Button ID="Button2" runat="server" Text="Add Record" OnClientClick = "return Validate(this)"
onclick="Button2_Click" />
The button gets disabled but the value isn't submitted into the database.
Database update code is
protected void Button2_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(500);
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true";
con.Open();
SqlCommand cmd = new SqlCommand("insert into expense values(#person,#item,#expdate,#price)", con);
cmd.Parameters.Add("#person", SqlDbType.VarChar);
cmd.Parameters.Add("#item", SqlDbType.VarChar);
cmd.Parameters.Add("#expdate", SqlDbType.DateTime);
cmd.Parameters.Add("#price", SqlDbType.Int);
cmd.Parameters["#person"].Value = droplist_person.SelectedItem.ToString();
cmd.Parameters["#item"].Value = txt_stuff.Text;
cmd.Parameters["#expdate"].Value = DateTime.Now.ToString();
cmd.Parameters["#price"].Value = txt_price.Text;
cmd.ExecuteNonQuery();
InsertHistory();
Response.Redirect("Add.aspx");
}
remove the UseSubmitBehavior="false" attribute?
and you dont need to return anithing in the javascript (return false is used to cancel a postback)
I think it's the way you are inserting the items into the database since you said that it disables the button but doesn't insert the database. So to me, that means the event is firing but something is wrong with the way you are inserting. This is how my buttons look, using your code..
protected void Button2_Click(object sender, EventArgs e)
{
string person = droplist_person.SelectedItem.Text;
string item = txt_stuff.Text;
string expdate = DateTime.Now.ToString();
string price = txt_price.Text;
System.Threading.Thread.Sleep(500);
SqlConnection con = new SqlConnection("Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO (expense person, item, expdate, price) VALUES (#person, #item, #expdate, #price)", con);
cmd.Parameters.AddWithValue("#person", person);
cmd.Parameters.AddWithValue("#item", item);
cmd.Parameters.AddWithValue("#expdate", expdate);
cmd.Parameters.AddWithValue("#price", price);
cmd.ExecuteNonQuery();
InsertHistory();
Response.Redirect("Add.aspx");
Button2.Enabled = false; //you can disable the button one the button click as well.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "mess();", true);
}
I would also surround that in a try/catch. Also, as far as I know, the Add is the "old" way of inserting items into the database. AddWithValue is going to be the best way since you are inserting items from drop downs and from text boxes. I think this is the where the problem lies. You can also put the connection inside the connection inside the SqlConnection like above to "clean" things up a bit. As to your "2nd" question, I'm not completely sure what you mean, but I hope this solves the problem to your 1st question.
EDIT: Added the disabling of the button since it was described in the title.
EDIT 2: Also, remove the UseSubmitBehavior="false" and the OnClientClick. Instead, you can call the message in the behind code.. Look above for example.
EDIT 3: From what I understand then, you will want to keep what the code the inserts the values. So keep the OnClientClick = "return Validate();" And then in your button click, disable the button. Then you will want to add if(!PostBack) to the page load, like so.. This will enable the button on the page load if the postback has happened. So what will be happening is that you disable the button, then once it posts back, it will be re-enabled.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Button2.Enabled = true;
}
}

how to capture javascript var value into asp.net page

I have an asp.net page on which at a click on Button (btn1), i want to show message box asking user a question "Do you want to overwrite ?" with button "Ok/Overwrite" and "Cancel" , and based on user response , i will have to update my database.
So i was trying to accomplish it using Javascript Confirm function
var r = Confirm('Do you want to overwrite ?)
but now i have to capture this Var r into my page so that i can update my database accordingly
any help how can i do it ?
On this scenario, you don't need to pass in the value of r to the server; you simply don't postback.
Just have something like this:
<asp:button id="btn1" runat="server" OnClientClick="return confirm('Overwrite?');" OnClick="btn1_Click" Text="Submit" />
If the users clicks "OK" then the page will post back and you will update the DB. If the user clicks cancel, the page won't postback at all and you won't have to do anything.
Here is your code:-
Add a hidden field in Net(.aspx) page
<form id="form10" runat="server">
<asp:HiddenField ID="hdnField" runat="server" Value="false" />
</form>
The hidden field should be added under Form Tag.The value of this hidden field is initially "false".
Here is what you need to do in Code Behind file (.cs file)
protected void btnSubmits_Click(object sender, EventArgs e)
{
if (hdnField.Value == "false")
{
AddJavascriptCode(itemValue);
}
else if (hdnField.Value == "true")
{
lblMsg.Text = string.Format("You have entered {0}", itemValue);
hdnField.Value = "false";
}
}
Here is the code to capture the response from OK/Confirm or Cancel button.
private void AddJavascriptCode(string itemValue)
{
string script = #"<script language=""JavaScript"" type=""text/javascript"">
window.onload=function()
{
var IsConfirm = 1;
objField = document.getElementById('" + hdnField.ClientID + #"');
objSubmit = document.getElementById('" + btnSubmit.ClientID + #"');
IsConfirm = newConfirm('Test','You have entered " + itemValue + #" value. Do you want to overwrite ?',1,1,0);
if(IsConfirm == true)
{
objField.value = 'true';
objSubmit.click();
}
else
{
objField.value = 'false';
}
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
}
}
Hope this helps you :).

Categories

Resources