Values are sent as null when using js prompt - javascript

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;
}
};

Related

Validate empty string in form

I have a form that takes the users input and concatenated that to a url (written in function). How do I check to see if the users value is empty and have an alert appear right below the form that says "Please enter a valid store URL". With out having to re write my entire function! Help!
Input form
<form id="url">
<input type="text" name="urlName">
<button onclick="return myFunction()">Try it</button>
</form>
Javscript Function
document.getElementById("url").addEventListener("submit", myFunction);
function myFunction() {
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
Check empty string I have not working
function valInput() {
if (input.value.length === 0){
alert("need valid store URL")
}
}
In myFunction you can simple add this code after creating a new instance of FormData:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You call the myFunction twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction.
And in HTML you don't need button. You can add input:submit which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>
You can add an onBlur handler to the input.
function validate(val) {
if(val.trim() === "") {
alert("Field is required");
}
}
<input type="text" name="urlName" onblur="validate(this.value)">

Compare viewbag value with string

I assigned value to a ViewBag.Form in a controller
ViewBag.Form = "In";
Now, I want to compare the value with string in javascript. So I do it like this
var form = "#ViewBag.Form";
if (form == "In")
{
//myCode
}
else
{
//myCode
}
But it always enter the else loop which mean form and ViewBag.Form doesnt match the value while it actually matched
please take viewbag in JavaScript in single quote
like this '#ViewBag.Form'
var form = '#ViewBag.Form';
if (form == "In")
{
//myCode
}
else
{
//myCode
}
or
assign ViewBag.Form value to hidden field
<input type="hidden" id="FormID" value="#ViewBag.Form" />
var form = document.getElementById('FormID'); //javascript
var form = $("#FormID").val(); //jQuery
if (form == "In")
{
//myCode
}
else
{
//myCode
}

Javascript Function in MVC

I am developing an Quiz Application in MVC 5. I have added two tables in database. One for marks and other for Questions and Answers. I have entered data in database for question, answers and have entered bool value as true or false for correct answer and vice versa. I am able to view Question and Answers from database.But I got stuck whenever user checks the checkboxes i want to give him points based on correct or wrong answer. I am not able to write javascript function in order to check whether the checkbox is checked or not.
Javascript:
function scorecheck(id) {
if (document.getElementById(id).checked) {
document.getElementById(id).value = "false";
}
else {
document.getElementById(id).value = "true";
}
}
Razor view:
#using(Html.BeginForm("Score", "Home", FormMethod.Post))
{
foreach (var item in Model) {
#Html.DisplayFor(modelItem => item.Question)
#Html.CheckBox("ans1", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans1)<br />
#Html.CheckBox("ans2", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans2)<br />
#Html.CheckBox("ans3", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans3)<br />
#Html.CheckBox("ans4", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans4)<br />
}
<input type="Submit" value="Submit" />
}
Also I have written logic for giving points for correct and wrong answer but it is not working.
C#:
int s = 0;
string ans1 = c["ans1"];
if (ans1 == "true")
{
s = s + 20;
}
string ans2 = c["ans2"];
if (ans2 == "false")
{
s = s - 20;
}
string ans3 = c["ans3"];
if (ans3 == "false")
{
s = s - 20;
}
string ans4 = c["ans4"];
if (ans4 == "false")
{
s = s - 20;
}
Here is how you can check the value of checkbox on click:
<input type="checkbox" value="yourvalue" onclick="MyFunc(this)">
and the javascript function:
function MyFunc(control)
{
if(control.checked==true)
//your logic
}
I have used following to get id from checkboxes:
`<input id="#(item.ans1)" type="checkbox" name="ans1" value="#item.ans1" onchange="scorecheck('#(item.ans1)')" /> `
Then I am using Javascript Function to check if its value is true or false like this:
if (document.getElementById(id).checked) {
document.getElementById(id).value = "True";
}
else {
document.getElementById(id).value = "False";
}

Trouble accessing data passed from another view, using MVC

I am attempting to pass data from one view to the other using MVC. I am trying to do a simple guessing game, where on the first view, we enter a range of numbers, then on the second view we try to guess the number. I am able to store the values in my model, but I'm having trouble accessing them/using them in a js script on another view. Sorry if this is too much code, MVC's are hard to ask for help on without showing a full range of code. When I go to the second view to guess the number, it doesn't recognize #ViewBag.(model => model.Low) and it says Load is not defined
Model
pubblic class Range
{
public int High
{
get
{
if (HttpContext.Current.Session["High"] == null)
{
HttpContext.Current.Session["High"] = 3;
}
return (int)HttpContext.Current.Session["High"];
}
set
{
HttpContext.Current.Session["High"] = value;
}
}
public int Low
{
get
{
if (HttpContext.Current.Session["Low"] == null)
{
HttpContext.Current.Session["Low"] = 1;
}
return (int)HttpContext.Current.Session["Low"];
}
set
{
HttpContext.Current.Session["Low"] = value;
}
}
}
Controller
public class GuessingGameController : Controller
{
public ActionResult EnterRange()
{
return View();
}
[HttpPost]
public ActionResult EnterRange(Range range)
{
int high = range.High;
int low = range.Low;
return View(range);
}
public ActionResult GuessNumber()
{
return View();
}
}
View 1: Enter Range
#model GameMVC.Models.Range
#using (Html.BeginForm("EnterRange", "GuessingGame"))
{
<center>
<h2>Lets play a game.</h2>
Enter A Range of Numbers:
<br />
Low: #Html.TextBoxFor(m => m.Low)
<br />
High: #Html.TextBoxFor(m => m.High)
<br />
<input type="submit" value="Enter"/>
<p>
#Html.ActionLink("Now, To the Game", "GuessNumber", "GuessingGame")
</p>
</center>
}
View 2: Guess Number
#model GameMVC.Models.Range
<script language="JavaScript">
var myNum, count;
function Load() {
document.game.status.value = "Please set range of numbers and press the Start button.";
document.game.number.focus();
}
function Round(scale) {
var dd = new Date();
return((Math.round(Math.abs(Math.sin(dd.getTime())) * 8.71 * scale) % scale));
}
function myRange() {
var to = 1 + 1 * #ViewBag.(model => model.Low);
count = 0;
myNum = Round(to);
while (myNum < #ViewBag.(model => model.High);)
myNum = Round(to);
document.game.status.value = "Please guess a number, enter it, and press Guess.";
}
function Guess() {
var numberGuess = document.game.number.value;
count++;
if (numberGuess < myNum) alert("My number is greater than " + numberGuess + ".");
else if (numberGuess > myNum) alert("My number is less than " + numberGuess + ".");
else alert("It takes you " + count + " attempts to guess this number");
}
</script>
<body onload=" Load() ">
<div style="text-align: center;">
<form name=game>
Guess: <input type="text" name="number" size=10>
<p>
<br/>
<input type="button" value="Guess" onclick=" Guess() ">
</p>
#Html.Label("status")
</form>
</div>
</body>
Instead of #ViewBag.(model => model.Low), you could try just using #Model.Low
Model instance is not provided for "GuessAction" view. You need to pass an instance of "Range" to "GuessNumber" view. Since you are accessing values from session, you can simply pass a new instance.
public ActionResult GuessNumber()
{
return View(new Range());
}
Then in javascript you can simply access the data as #Model.High and #Model.Low
You can also use TempData to store the high and low values if you need it only for one request.

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

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".

Categories

Resources