Do not propagate conversation manually +CDI +JS2 +WELD - jsf-2

I have a xhtml with a form with a backing bean running in ConversationScoped.
I want create a FORM that submits and do not propagate the conversation (CID).
On the generated html the CID appears in the action on the form tag:
<form id="forme" name="form_nova_senha" method="post" action="/plma/index.xhtml?cid=1" enctype="application/x-www-form-urlencoded">

I found reading source of WeldPhaseListener
public static String getConversationId(FacesContext facesContext, ConversationContext conversationContext) {
Map<String, String> map = facesContext.getExternalContext().getRequestParameterMap();
if (map.containsKey(NO_CID))
return null; // ignore cid; WELD-919
String cidName = conversationContext.getParameterName();
String cid = map.get(cidName);
log.trace(FOUND_CONVERSATION_FROM_REQUEST, cid);
return cid;
}
Just need to put the nocid paramenter on request.

Related

Parameter passing in an MVC Controller

I have the following ActionResult in my controller
[HttpGetAttribute]
public ActionResult _UpdateAlertNote(int recordId)
{
DealActionUpdateAlertNoteViewModel vm = new DealActionUpdateAlertNoteViewModel();
dtDeal_v10_r1.Manager objMan = new dtDeal_v10_r1.Manager(ref mobjSecurity);
dtDeal_v10_r1.Deal objDeal = default(dtDeal_v10_r1.Deal);
objDeal = objMan.GetDealObject(recordId, true);
vm.Message = objDeal.AlertMessage;
vm.IsDefaultStyle = objDeal.Alert_UseDefaultStyle;
vm.BackgroundColor = objDeal.Alert_BackgroundColor;
vm.FontColor = objDeal.Alert_FontColor;
vm.DealId = recordId;
return PartialView(vm);
}
Also the following ActionResult
[HttpPost]
public ActionResult _UpdateAlertNote(DealActionUpdateAlertNoteViewModel vm)
{
dtDeal_v10_r1.Manager objMan = new dtDeal_v10_r1.Manager(ref mobjSecurity);
objMan.UpdateAlertMessage(vm.DealId, vm.Message, vm.IsDefaultStyle, vm.FontColor, vm.BackgroundColor);
return this.PartialView("_action", vm.DealId);
}
When I execute this code it the "DealId" comes up as 0 in the Post.
I checked the Get and the DealId is being stored in the vm.DealId but is not passed through to the Post method.
I am not sure why it isn't passing could someone help me out with this.
****EDIT json added***
DealerSocket.TakeAction.updateDealAlertNote = function () {
var controller = "/DealAction/_UpdateAlertNote?mDeal_ID=";
var formId = "_UpdateDealAlertNoteFormElement";
DealerSocket.TakeAction.PostActionAndRefresh(formId, controller);
};
When you are posting an HTML Form element to a POST action, you need to make sure the value you pass to the view is stored in a Form element.
In this case of yours you will need something like:
<input type="hidden" value="#vm.DealId" />
within the <form> tag that you are Posting to the action.
Only elements inside the <form> tag will be serialized and sent to the Action.

pass value of a textbox from view to controller using actionlink

In my form I have a textbox as below
#Html.TextBox("first_name")
I need to pass the value of this textbox to controller through a actionlink.
I tried the below
#Html.ActionLink("View", "view_Details", new { name = first_name})
but this is giving error
"first_name" does not exist in the current context
Is this possible using a Actionlink?
My controller signature is
public ActionResult view_Details(string name)
{
return View();
}
Edited
#Html.ActionLink("View", "view_Details", new { name = getname()})
<script type="text/javascript">
function getname() {
return $("#first_name").val();
}
</script>
I tried above code. Its also giving error
getname() does not exist in the current context
You need javascript/jquery to get the value of the textbox and then update the url you want to redirect to
Html
#Html.ActionLink("View", "view_Details", new { id = "myLink" }) // add id attribute
Script
$('#myLink').click(function() {
var firstname = $('#first_name').val(); // get the textbox value
var url = $(this).attr('href') + '?name=' + firstname; // build new url
location.href = url; // redirect
return false; // cancel default redirect
});
Side note: further to you edit, the reason you receive that error is that razor code (the #Html.ActionLink() is parsed on the server before its sent to the view but getname() is a client side method which does not exist at that point - i.e it does not exist in the current context

Postback for the second time from asp.net MVC view

Setup:
I am working on reset password page and planning to have a single view to display three forms one after another.
Initially user will be asked to enter username, then the form gets submitted.
I am able to capture it is HttpPost action method.
I am returning the same view but this time I am rendering a different form, I am doing this using Razor
When I try to submit (calling a different action method) from the second form that I am displaying now I am getting and error saying that Resource cannot be found
Question:
Is it not possible to post back twice from the sample page/view?
If possible how can I achieve it?
CSHTML:
#if (ViewBag.step == 1) {
<form id="frmUsername" action="#Url.Content("~/Account/ValidateAnswers")" method="post" novalidate="novalidate" ng-init="initStep1()">
...
</form>
}
#if (ViewBag.step == 2) {
<form action="#Url.Content("~/Account/ValidateUsername")" id="frmQuestions" ng-init="initStep2()" novalidate="novalidate">
...
</form>
}
Controller methods:
public ActionResult RecoverPassword(string userType)
{
ViewBag.step = 1;
ViewBag.userType = userType;
ViewBag.showUsernameErrorMessage = "false";
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult ValidateUsername(string userName, string selectedUserType)
{
...
ViewBag.step = responseStep;
ViewBag.showUsernameErrorMessage = responseShowUsernameErrorMessage;
ViewBag.userName = userName;
ViewBag.userType = selectedUserType;
return View("~/Views/Account/RecoverPassword.cshtml");
}
[HttpPost]
public ActionResult ValidateAnswers(string answer1, string answer2, string answer3, string questionId1, string questionId2, string questionId3, string step, string userName, string selectedUserType)
{
...
ViewBag.step = responseStep;
ViewBag.showUsernameErrorMessage = responseShowUsernameErrorMessage;
ViewBag.userName = userName;
ViewBag.userType = selectedUserType;
return View("~/Views/Account/RecoverPassword.cshtml");
}

Troubleshoot MVC model binding failure - argument is null in controller

I am trying to POST an object from a WebJob to an MVC 4 controller. I am using Entity Framework. In the controller, I cannot get the object to bind properly (the argument is null). I have looked at many tutorials and it seems like my code should work.
Model (does this need to be in a specific namespace for EF to find it?):
public class CreateListingObject
{
public Listing listing;
public List<GalleryImage> images;
public CreateListingObject()
{
listing = new Listing();
images = new List<GalleryImage>();
}
}
public struct GalleryImage
{
public string picURL;
public string caption;
}
POST:
public void PostListing(CreateListingObject o)
{
Console.WriteLine("Posting listing: {0}", o.listing.Title);
HttpClient _httpClient = new HttpClient();
Uri uri = new Uri(_serviceUri, "/Automaton/CreateTestListing");
string json = BizbotHelper.SerializeJson(o);
HttpResponseMessage response = BizbotHelper.SendRequest(_httpClient, HttpMethod.Post, uri, json);
string r = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
}
SendRequest (thank you Azure search samples):
public static HttpResponseMessage SendRequest(HttpClient client, HttpMethod method, Uri uri, string json = null)
{
UriBuilder builder = new UriBuilder(uri);
//string separator = string.IsNullOrWhiteSpace(builder.Query) ? string.Empty : "&";
//builder.Query = builder.Query.TrimStart('?') + separator + ApiVersionString;
var request = new HttpRequestMessage(method, builder.Uri);
if (json != null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
return client.SendAsync(request).Result;
}
Controller Action fragment (o is an empty object here):
[HttpPost]
public ActionResult CreateTestListing(CreateListingObject o)
{
Listing li = o.listing;
I have confirmed that if I post a simple object using the same code, everything works as expected.
Instead of sending a CreateListingObject in PostListing, I send this instead:
var test = new
{
data = "hi mom"
};
And change my action to, then the argument gets bound and I get valid data:
[HttpPost]
public ActionResult CreateTestListing(string data)
{
I have also checked the serialization of my CreateListingObject in the WebJob, and it is fully populated as I expect. This leads me to suspect that I am falling afoul of the default ModelBinder.

ASP. Net MVC and RegisterClientScriptBlock alternative

I currently have a web form aspx page that calls RegisterClientScriptBlock. This sends down message text that I use for client side validation e.g.
<script type="text/javascript">
//<![CDATA[
var c_errorMessages = {
RequiredField : "* Mandatory field"
};
//]]>
</script>
The values are generated on the server side based on culture and resource files.
I believe you cannot use RegisterClientScriptBlock with MVC.
Any ideas on how I can achieve this with MVC?
The validation that comes with ASP.NET MVC 2 has built-in support for localized validation messages when using client-side validation. This will take care of registering the client scripts.
Having said that, the most common way to do this in ASP.NET MVC would probably be to simply have the controller feed the view with the data required to render the client script. An example of this would be
Action method in controller:
ViewData["MessagesToClient"] = new[] { "Abandon", "All", "Hope" };
return View("MyView");
Some code in MyView.aspx:
<%= RenderPartial("MyPartialView") %>
Some code in MyPartialView.ascx:
<script>
<% foreach (var message in (IEnumerable<string>)ViewData["MessagesToClient"]) { %>
alert("<%= message %>");
<% } %>
</script>
This way, MyView.aspx doesn't necessarily need to know about the data MyPartialView.ascx needs.
Create an extension method for HtmlHelper which takes your model and renders the javascript.
If you are doing validation:
Have a look at Castle Validation attributes. http://castleproject.org.
You can add attributes to your model (class) ...
[ValidateNonEmpty]
public string Name { get; set; }
and your extension method can determine the presence of these and write the appropriate javascript / jquery.
public static string JSValidation<T>(this HtmlHelper<T> html, T model) where T : class {}
And in your view use the helper:
<%= Html.JSValidation(Model) %>
ASP.NET MVC in Action has a brilliant example of this in Chapter 13.
Thanks for answer bzlm. My solution is pretty much the same as yours except I am not using a user control
In my controller I add to viewdata(this would be generated from method):
ViewData["javascriptBlockRequired"] =
"\r\n<script type='text/javascript'>\r\n//<![CDATA[\r\nvar c_merchant = { \r\n\tSomeField: false};\r\nvar c_errorMessages = {\r\n\tRequiredField : '* Required' \r\n};\r\n//]]>\r\n</script>\r\n";
In my view I output the script at the start of the body:
<body>
<%= ViewData["javascriptBlockRequired"] %>
....
<body/>
1- Add Extentions methods class
public static class Extentions
{
public static void AddRegisterClientsSript(this HtmlHelper helper, string key, string script)
{
Dictionary<string, string> scripts;
if (helper.ViewBag.RegisterClientsSript != null)
{
scripts = (Dictionary<string, string>)helper.ViewBag.RegisterClientsSript;
}
else
{
scripts = new Dictionary<string, string>();
helper.ViewBag.RegisterClientsSript = scripts;
}
if (!scripts.ContainsKey(key))
{
scripts.Add(key, script);
}
}
public static MvcHtmlString RegisterClientsSript(this HtmlHelper helper)
{
var outScripts = new StringBuilder();
if (helper.ViewBag.RegisterClientsSript != null)
{
var scripts = (Dictionary<string, string>)helper.ViewBag.RegisterClientsSript;
foreach (string script in scripts.Values)
{
outScripts.AppendLine(script);
}
}
return MvcHtmlString.Create(outScripts.ToString());
}
public static MvcHtmlString Paging(this HtmlHelper helper, string uniqId)
{
helper.AddRegisterClientsSript("jquerypaginatecss", #"<link href=""/Content/Paginate/jquery.paginate.css"" rel=""stylesheet"" />");
helper.AddRegisterClientsSript("jquerypaginatejs", #"<script src=""/Content/Paginate/jquery.paginate.js""></script>");
}
}
2- Add the namespace in page and use it
#using Mirak.Ui.Components
#section scripts{
#Html.RegisterClientsSript()
}

Resources