JSF Link Parameter get null - url

I have a page with link http://localhost:8080/Test/Page.faces?id=asdasdasd
The page got 2 text field and one button, after user key in the details and click submit, it works well when you first time click the submit button, the id will return me the exact value, but if the user never enter the value and click submit the validation will be invoked and next click the button again the id return null? How to solve this problem anyone can help?

Yes, when the user clicks on the button, the browser does a new request to the server. That new request doesn't have the ?id=asdasdasd as part of it. The easiest solution I can think of is to store that value into a hidden text field on the page. You can use some javascript to populate the value.
So, if you have a <h:hidden id="idHidden" value="#{mybean.idHidden}"/> on your JSP, maybe some javascript like this:
<script type='text/javascript'>
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
if(gup('id') != "") {
document.forms[0].idHidden.value = gup('id');
}
</script>
I haven't checked this code for errors, but the idea is the first time the page loads, the value of 'id' is stored in a hidden input field. That field is bound to your managed bean so the value is persisted across page refreshes. Just reference the id value stored on the bean (as idHidden in the example above) instead of the request parameter.
BTW: I stole the GUP function from http://www.netlobo.com/url_query_string_javascript.html
Nick

Related

How to check route parameter exists in layout page asp.net MVC

I have 2 parameters in url id & text. I am trying to check whether 'text' exists in layout page because initially I will have only Id and later I am addding 'text' to url from different action but same controller.
I have following code in my layout page but it works only when both parameters are available.
var Newid,Newtext;
Newid = ViewContext.RouteData.Values["id"];
Newtext = ViewContext.RouteData.Values["text"].ToString();
I am trying to check when my url is localhost:8122/products/12
#
{
if(ViewContext.RouteData.Values["text"].ToString()!=null)
{
}
}
but it gives object reference error.
I have to include .tostring() since I am checking like below in the same page
#if (Newtext =="t") {}

Reading value from cookie in asp.net core 1.0.1

I am storing full name of user in cookie after user successfully logs in with following code.
var res = await _signInManager.PasswordSignInAsync(suser.UserName, user.Password, user.Remember, false);
if (res.Succeeded)
{
Response.Cookies.Append("fullName", suser.FullName);
if (string.IsNullOrWhiteSpace(returnUrl))
return RedirectToAction("Dashboard", "User");
else
return Redirect(returnUrl);
}
I want to read this value in _Layout page so that I can display full name in master page. According to solution mention in this post. I tried following sysntax in my _Layout page.
#inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
#{
ViewBag.FullName = HttpContextAccessor.HttpContext.Request.Cookies["fullName"];
}
But I am not getting any value in ViewBag.FullName. Am I doing something wrong here? How to read stored value in cookies in Views?
I´ve done some tests to get the same result as yours.
The way I see it, you´re appending a new cookie value to the Response.Cookie and trying to access it in the Request.Cookies, so, the added value ("fullname") will only be available in the next request (after a redirect). If you try to access it in a View rendered at the same request that you set the cookie, the cookie value will be null.
I did the test with "return View()" and with "return RedirectToAction", only the second one worked.
I see that in your code you´re doing a redirect, I advice to debug it and see if the code is actualling entering in that line of code, if it is, go to that action that you are redirecting and, debugging it, see if the Request.Cookies are ok.
Regards.

Symfony Form reset after submit

I have a very simple form created with createFormBuilder providing one simple text field only (there is no entity attached to the form).
When the form is submitted I do some logic and then unset form and formData as suggested in many posts to this topic if you want the form to be reset after submitting.
There is some additional action by simple ajax-requests that mainly initiates some UI stuff - not touching the form itself nor reloading the page.
Everything works fine except that the form apparently just doesn't want to be reset - meaning: Whenever the page reload button in the browser is pressed the standard browser dialog appears that asks if you want to submit the form again. And when you do the last value typed in BEFORE the last render call is submitted.
The template kw.html.twig is straight forward - mainly some UI stuff the form rendering and a bit jquery for handling ajax. Nothing special there.
I can't figure out why this is happening - I just want a clean form on any request. Which I thought I get when unsetting thing like in the sample code below.
/**
* #Route("/kw", name="show_kw")
*/
public function showKwAction(Request $request)
{
if($request->isXmlHttpRequest()) {
if( $request->getMethod() == 'POST' ) {
// do some logic...
return $this->json(array('kw_success' => true));
}
}
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
if( $request->isMethod('POST') ) {
$kwForm->handleRequest($request);
$formData = $kwForm->getData();
// do some logic with formData...
unset($kwData);
unset($kwForm);
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
}
$templateData = array(
'kwForm' => $kwForm->createView()
);
return $this->render(':backend:kw.html.twig', $templateData);
}
Any help is highly appreciated.
EDIT: Using Symfony 3.1
It's exactly what Alsatian said in the comment. Browser is trying to repeat last request.
However I think that instead of destroying this form you can simply redirect to the same route with $this->redirectToRoute once you processed data, of course if it's not a problem.
Also I see you check at least twice if method is post. If it's not colliding with the rest of your application logic you can specify #Method("POST") in annotation so you don't have to check it directly in code anymore.
Best Regards,
R.

ASP.NET MVC3 Model Error (Previous value in error message)

I'm using ASP.NET MVC 3. I have an integer field and as a test I am entering character values in the text box which are invalid for ints.
So when I test,
I enter an invalid value and click submit.
MVC passes back the following error message:
The value 'FF,' is not valid for FCode.
So then I erase the FF from the form field and enter HH, then click submit. And then MVC gives me the following messages:
The value 'FF, HH' is not valid for FCode.
Then say I change the form field to BB, I get the following error returned:
The value 'HH, BB' is not valid for FCode.
It is always returning the latest 2 in the error message. How can I fix this to only return the latest 1? Users don't want to see their previous mistakes, they only want to see most recent.
Here is the code from my controller:
if (ModelState.IsValid){
//Do valid stuff here
}
else
{
var query =
from val in ModelState.Values
where val.Errors.Count == 1
select val.Errors;
foreach (var error in query.ToList())
{
errorList.Add(error[0].ErrorMessage);
}
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
return Json(errorList);
}
I was actually binding to same field in the model twice. That is what was causing this. I was using a TextBoxFor and a HiddenFor on the same field.
So when MVC sent the model errors back to my controller on form submit, it was sending 2.
I changed my TextBoxFor to a TextBox and this solved the problem since it is now only bound to the hidden.

In MVC, how can I make a field in a model non-required after a checkbox is checked?

I have a page written using .NET MVC. In the model for a Person called PersonModel I have this defined which requires the user to enter some text in the last name field:
<DisplayName("Last Name"), Required()> _
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
On the form, there is a checkbox that a user can check to do some other things. Is there a way, using JQuery preferablly, to change that Last Name field to be non-Required? If not using JQuery I am open to other suggestions but since I am doing alot of things when this check box is checked anyways, I was hoping I could add this logic in there. Here is some sample of what I am doing when this box is checked to demonstrate...
function doOwnerBusiness(event) {
if ($(this).is(':checked')) {
$('input[name="People_1__LastName"], label[for="People[1]_LastName"]').hide();​
$("#People_1__LastName").hide();
$("#People_1__LastName").val("");
$("#People_1__LastName :input").attr('disabled', true);
$('input[name="People[1]_Suffix"], label[for="People[1]_Suffix"]').hide();​
$("#People_1__Suffix").attr('disabled', true);
$('#People_1__Suffix')[0].selectedIndex = 0;
$('#People_1__Suffix').hide();
}
else {
$('input[name="People_1__LastName"], label[for="People[1]_LastName"]').show();
$("#People_1__LastName").show();
$('#People_1__LastName :input').attr('disabled', false);
}
}
Any help with this would be appreciated folks.
Thank you
William
Here is how I am declaring my checkbox and also part of the function where I am trying to check if it is checked or not...
<%=Html.CheckBoxFor(Function(model) model.FirstNameAsBusiness)%>
<%=Html.LabelFor(Function(model) model.FirstNameAsBusiness)%>
Function Nominate(ByVal m As NominationModel, ByVal captchaValid As Boolean) As ActionResult
If Not m.FirstNameAsBusiness.checked AndAlso String.IsNullOrEmpty(m.lastnametext) Then
ModelState.AddModelError("LastName", "Last Name field is required if you don't yada yada...")
Return View()
End If
Short answer: no. You can't bypass the DataAnnotation with a jQuery call.
Technically, the Last Name field isn't required. So, I'd remove the DataAnnotation for Required, and then on the backend, when the user submits the form, verify that a field value exists when the checkbox isn't checked. If the conditional doesn't pass, and an error to ModelState for that field, and redirect to the page. (apologies for the c#):
public ActionResult Index(HomeIndexModel form)
{
if (!form.Checked && string.IsNullOrEmpty(form.LastName))
{
ModelState.AddModelError("LastName", "Last Name field is required if you don't yada yada...");
return View();
}
//conditional requirement passed...
}
If you want to get a little fancier, you can check out this thread, though all of the suggestions here are also server-side:
ASP.NET MVC Conditional validation

Resources