How to do conditional required field validations in ASP.net MVC2 - asp.net-mvc-2

I have 2 , one is update user details another is change password panel. Both has separate "update" button. I don't want user details part to be validated when I click on update button of change password and the vice versa applies the same. Presently I am using the following code in View.
[Required]
[DataType(DataType.Password)]
[DisplayNameLocalized(typeof(CapnorResource), "RepeatNewPassword")]
public string RepeatNewPassword { get; set; }
in UI following is the code.
<div class="passwordtd">
<%: Html.LabelFor(view => view.RepeatNewPassword)%>
<%: Html.PasswordFor(view => view.RepeatNewPassword)%>
<%: Html.ValidationMessageFor(view => view.RepeatNewPassword)%>
</div>

I'm not quite sure from the wording of the question, but with two different buttons, it sounds like two different forms with two different ViewModels. The ViewModels could make up one large ViewModel, or you could use RenderPartial to separate them completely.

I had same scenario with little twist.
I had a single Account page and change password is a rendered as partial inside the main page, the change password has its own update button and the partial is rendered inside a div id="secure" tag which gets hidden in $(document).ready(). There is a link on main account details page which unhides the div.
I acheived partial validation as follows.
1)Created a temporary div out side the form tag.
2)On $(document).ready() I append the change password partial to the temporary div so when the main Account Details validation are fired the change Password's validation are not fired.
3) when the link to unhide the change password partial is clicked I again append the change password partial to form and then on Update button of change password partial I manually call validation mehods
var validator = $("form").validate();
var oldpass = document.getElementById("OldPasswordfeild");
var newpass = document.getElementById("NewPasswordfeild");
var conpass = document.getElementById("ConfirmPasswordfeild");
if (!validator.element(oldpass) || !validator.element(newpass) || !validator.element(conpass))
{
isvalid = false;
}
so only change password partials validation are fired and if they are valid I make a ajax post to my controller and if it is successful hide the div and again append it to temporary div out side the form.
Above thing works like a charm.

Related

In-line item editing in Lift / handling 2 different form submit needs on one page

OK, so first off, let's start with me acknowledging that the bind( ... ) way of binding Lift forms is so last week! :) I do know that, and I just haven't gone back to update this code yet. Also, I trust now that there's some really slick Lifty way to do this. That's what I seek. I'm stumped as to even how to hack something together. That said...
I have a list of Items that I initially display non-editable, and the title of each Item is an ajax-enabled link that calls to the server and replaces that line-item with an editable form of the Item (I use SetHtml to swap the form in at the < li> that listed that Item).
"parent" Items List view looks something like this
< form data-lift="form.ajax">
< div data-lift="creategamewizard?multipart=true" id="wizardform">
< ul>
< li>Item 1< /li>
< li>Item 2< /li>
< /ul>
some more form elements
< button>Submit< /button>
< input type="hidden" id='298356928734' />
< /div>
< form>
This ajax submit (via the hidden field) calls processSubmit().
The SetHtml that swaps in the editableItem form looks something like this.
NOTE: At the end of the following listing, the "save" binding has no server-side code tied to it because the "parent" submit button is already on the page, and when I put another hidden field in this binding or tried to tie any code directly to the Edit Item Save button, that code and the "parent" submit got triggered. So the approach below was to try to use the "parent" submit for both the parent submit as well as the Edit Item submit.
<a href="javascript://" onclick={ajaxOnClickHandler(editItemClickHandler(item.id.get))}>{item.title.get}</a>
def ajaxOnClickHandler(jsHandler: ()=>JsCmd) =
{
SHtml.onEvent( e => jsHandler()).toJsCmd+";return false;"
}
def editItemClickHandler(itemId: String): ()=>JsCmd = ()=>
{
trace.logAjaxComm("ExistingItem.Edit()")
JsCmds.SetHtml("LiId"+itemId, getEditableItem(promo) )
}
def getEditableItem(itemId) =
{
bind( ...
"promotitle" -> SHtml.text(editablePromo.get.promotitle.is,
(s:String) => {
trace.logUIDataManipulation("Saving new promo Title["+s+"]");
editablePromo.get.promotitle(s)
}, "id" -> "promotitle"),
"save" -> SHtml.button("Save", ()=> {})
)
}
Then when the user selects an Item, and the editable Item form is plugged in, there's "another" submit button that should ajax submit the form data for that item, and then swap back in the (now updated) nonEditable version of the data.
The problem for me is the submission. In addition to the Edit Item form above, I've got a ajaxified submit button on the "parent" non-editable list page to handle submitting some fields below the list. The Edit Item "save"-> binding adds a button, which should do (and in fact does) nothing for itself, but it does trigger the "Parent" submit button. And I route that submit to do the save of the Edit Item form.
The non-editable Item and the editable item code swaps fine, but changes made in the editable Item form is not saved, and I figured out that that was happening because the elements in the editable Item form are not being submitted at all, following is an example of a log message I don't see at all...
bind( ... "promotitle" -> SHtml.text(editablePromo.get.promotitle.is,
(s:String) => {
trace.logUIDataManipulation("Saving new promo Title["+s+"]");
editablePromo.get.promotitle(s)
}, "id" -> "promotitle")
)
In a normal ajaxified form, all element handlers are called (if there are changes to the field, I guess...) in order of rendering, with the submit/hidden elements' handlers being called last (if they're last in the bind list.
so finally, let's get around to my question:
if you're doing in-place editing like this, how do I manage 2 submit buttons (the one for the non-editable list page plus the additional one that gets added when editing an item)?
I'm sure I don't need to refresh the page, but I can't figure out how you'd do this with Ajax.
Maybe alternatively, the in-place editable form can be submitted as a non-submit ajax action, ie. somehow that doesn't trigger the parent submit?
For anyone tripping over this question, I figured I'd share the solution I eventually found...
1)The problem was that the submit (for AJAX this is the hidden html tag) happened before the editable Item's field handlers were called. So when the AJAX update that collapsed the editable Item back into just a non-Editable list item, the data hadn't yet been updated. So what was displayed in non-editable form didn't show the update, yet if I refreshed the page in the browser, the update had been saved to the database and now showed properly.
2)The reason for the mal-ordering is that Lift assigns each form tag's server-side handler an id (which are "monotonically increasing" with an additional string added to the end). That's fine until you do an ajax live-update of a form and add fields (as I did when I inserted the Editable Item fields). These newly-added fields were assigned server-side ids that came after the hidden field that got generated as part of the initial page rendering.
3)The solution was to explicitly shove the hidden field into a much higher id using S.formGroup. See here for more details...
The example from the last link below is as follows (and differs from mine in that it uses SHtml.submit, whereas I use SHtml.hidden). It adds the constant 1,000 to the submit button's server-side handler id:
"type=submit" #> S.formGroup(1000) {
SHtml.submit("Submit", process)
}
Discussion of a problem that is essentially the same as mine: https://groups.google.com/forum/#!topic/liftweb/MYJQeVlOYFM
Description of id assignment and S.formGroup under heading "Server side function order.":
https://www.assembla.com/spaces/liftweb/wiki/cool_tips
And lastly, linked to from the last link is some example code:
https://groups.google.com/forum/#!topic/liftweb/E9z7PVhogQw

How to reuse codeigniter form on multiple pages

I have a simple search form I want to reuse across multiple pages in my codeigniter application. For example, right now I have a search form in the sidebar and I'm planning on displaying that sidebar on the index, about, and other pages.
I want to have the form validation display errors on the same page the users submits the form from.
For example:
User is on About page.
User submits form with invalid data
User sees error in the sidebar on the About page
and
User is on Index page.
User submits form with invalid data
User sees error in the sidebar on the Index page
But I'd like to reuse that form validation logic. I just want it to display the error on whichever page the user posted from.
Any ideas how to do that? Sorry for the noob question, I'm pretty new to CI.
Here you have to think globally.
Step.1 : Make one view file : display.php
which contains :
<div id = "main">
<div id = "header">
[load header file here]
</div>
<?php
if(validation_errors() != '') {
?>
<div id = "error">
<?=validation_errors()?>
</div>
<?php
}
?>
<div id = "content">
<?=$page?>
</div>
<div id = "footer">
[load footer file here]
</div>
</div>
Step.2 : About us Page.(controlller)
.... Your data ....
at end of controller function
$data['page'] = 'aboutus';
$this->load->view('display',$data);
With regards to your comment on the above question you could use Flash data
With the assumption that you have the session library loaded, here is a helper function.
function last_page($page = null){
$ci = get_instance();
if($page === null)
return $ci->session->flashdata('last_page');
$ci->session->set_flashdata('last_page', $page);
}
then you can call last_page('about'); at the top of the about page, and then when you want to find out what the last page you were on was you can just call last_page(); with no params.
In the User Guide, there's different ways to configure sets/groups of rules. Then you can simply have something like:
if ($this->form_validation->run('signup') == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
Which will run your "signup" group of validations. To me, this is the cleanest way to achieve reusable validation rules.
This is a perfectly valid question.
I'm not a PHP expert, nor a CI expert, but the fact is sometimes you want to post to a controller that didn't create the view from which you're posting. Which means posting back to itself is not going to work.
I came across this post on the Ellislab forum:
http://ellislab.com/forums/viewthread/217176/
On this page, There are 2 methods of going about it. Both of which use flashdata and both of which are totally valid, IMHO.
The first: create a helper function
http://ellislab.com/forums/viewreply/1003010/
The second: extend the CI_Form_Validation Class.
http://ellislab.com/forums/viewreply/1047536/
The second is the way I went as it seems cleanest although some may argue whether the form validation class should know anything about flash data.

Validation Forms that were loaded via Ajax into jquery-ui tabs

I'm using jquery-ui tab example to add extra tabs. I changed that code to be able to add tabs that load a form via Ajax. I was able to create that just changing these:
var $tabs = $( "#tabs").tabs({
cache: true,
tabTemplate: "<li><a href='formularioAgricola.php' id='#{label}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>"
//ajaxOptions: a
});
So I changed the tabTemplate to load the same Form always.
My problem is that I'm not sure how to retrieve, either to tell that every tag from that form use jquery-ui stuff, like buttons, datepickers, etc.
In a regular form I would do something like:
$("#btnRevisar").button()
But when we talk about form load via Ajax it is different.
and also, how can I try to differ one form from other one, if they are all named with the same name, is it possible?
Thanks guys
Carlos.
Within the tabs docs page, tab titled "Events" there is a "load" event. The "ui" argument gives you access to an object that includes the current panel that is loaded. If you are using same ID on forms, beware that ID's must be unique in a page.
var $tabs = $( "#tabs").tabs({
cache: true,
tabTemplate: "<li><a href='formularioAgricola.php' id='#{label}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
/* add new option for load event*/
load: function( event, ui){
var $currTabContentPanel=$(ui.panel);
/* only look in currently loaded content for formClass*/
$currTabContentPanel.find('.formClass').doSomething()
}
});

Make form submit with addition parameters. ASP.NET MVC

I would like to submit form by click on the button 'Submit'. All ok, but I have addition checkboxes without binding to model. This checkboxes were added dynamically. How to send form to client with these checkboxes and grab data on server.
[HttpPost]
public ActionResult Add(PremiumSlots PremiumSlots, FormCollection collection)
{
string chkbx = collection["yes-no"];
// "yes-no" name of checkbox (Should be same for all checkboxes)
// you will get comma separated values, perform split operation on string and use individualy
}

Enabling/Disabling CSS based on Session value using MVC

I am rather new to MVC applications, and one thing I am trying to accomplish is enabling or disabling stylesheets based on a Session value.
I have stylesheets referenced in my Site.Master page in this manner:
<%=Html.Stylesheet("~/styles/main.css", "string")%>
<%=Html.Stylesheet("~/styles/additions.css", "string")%>
Right now, for testing, I have been putting an if statement around the Html.Stylesheet tags saying:
<% if (Session["cssRule"] = "enableCss") { %>
<%=Html.Stylesheet("~/styles/main.css", "screen")%>
<%=Html.Stylesheet("~/styles/additions.css", "screen")%>
<%} %>
So if the 'cssRule' Session value is null, no CSS loads. Currently this is working fine, but it is not exactly what I am looking for. Right now I set the Session value in the Controller when the user logs in, but ultimately I need to set the value of the Session variable depending on if a user clicks the enable or disable button. Since I have been primarily using webforms for the past year and a half, I just want to drop a hyperlink and set an event for it, but alas, this is the future of MVC so I need to figure out how I can do something like this..
So my real question is how can I set the Session of the "cssRule" value by clicking a link using MVC?
I'll assume you want to use a standard link (not ajax) and that your main view is Index
Just add a method in your controller (pseudocode)
public ActionResult ToggleCSS()
{
if (Session["cssRule"] != null && Session["cssRule"] == "enableCSS")
{
Session["cssRule"] = "disableCSS";
}
else
{
Session["cssRule"] = "enableCSS";
}
return View("Index");
}
Then in your view, use
<%= Html.ActionLink("ToggleCSS", "ControllerName") %>
You can use lots of fancy different methods to obtain the same result; use ajax and relaod the page, or not, or redirect to a page listing css files to apply, etc... but this one should work :)