Pass multiple values during change event of <select> - ajax

Dropdown list 1:
<select name="ddlArea" onchange="showState(this.value)">
Dropdown list 2:
<select name="ddlFType" onchange="showState(this.value)">
I want to get selected values of both dropdown lists in showState function. I want to invoke same function as the ajax request will be processing on different page which requires both the parameters Area and FType.
Function:
function showState()
{
var area_value = document.getElementById("ddlArea").value;
var ftype= document.getElementById("ddlFType").value;
if(document.getElementById("ddlFlat").value!="-1" )
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="vacant_do.jsp"
url=url+"?area_id="+area_value+"ftype"+ftype
xmlHttp.onreadystatechange=stateChange
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
else
{
alert("Please Select Area Name");
}
}
function stateChange()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState==200)
{
document.getElementById("ddlFlat").innerHTML=xmlHttp.responseText
}
}

Since you are just trying to invoke an AJAX Query with 2 parameters, I wouldn't push in the value through the onChange.
Combo -Box 1:-
<select name="ddlArea" id="ddlArea" onchange="showState()">
Combo -Box 2:-
<select name="ddlFType" id="ddlFType" onchange="showState()">
and then:
function showState() {
var area = document.getElementById('ddlArea').value;
var fType= document.getElementById('ddlFType').value;
....invokeAJAX request....
}
You COULD do this via some sort of prototype/closure method, but really, you already know where to get the information from, and it's not going to change on the page

Related

AngularJS Form Validation inside an ng-repeat

So I am trying to validate the input of one item inside of an ng-repeat. For examples sake lets say that I have 5 items (1,2,3,4,5) and I only want to validate the form if the 4th item is selected.
I have used ng-pattern before to validate forms, but not one that had a dropdown menu to select item.name
I have included the regex I would like the 4th item to be validated with inside the ng-pattern.
<div>
<select name="name" ng-model="item.name" ng-options="item for item in items" required></select>
</div>
<div>
<input name="results" type="text" ng-model="item.results" ng-pattern="/^\d\d\d\/\d\d\d/" required>
</div>
Any suggestions as to the correct way to validate this situation would be greatly appreciated. I have thought about creating a directive to validate this, but that feels like is an overly complicated solution to this since I would not use the directive more than once in this app.
//////////////////////////////////////////////////
It wouldn't let me answer my own question so here is the answer I figured out.
What I ended up having to do was use ng-pattern and pass it a function.
<input name="results" type="text" ng-model="vital.results" ng-pattern="vitalRegEx()" required>
Here is the controller code
$scope.item4RegEx = /^\d{2,3}\/\d{2,3}$/;
$scope.itemRegEx = function() {
if($scope.item && $scope.item.name === "fourth item")
return $scope.item4RegEx;
else return (/^$/);
};
or else...
add ng-change directive on the select dropdown which calls a Controller method and that controller method sets a flag whether to validate form or not.
eg.
<select ng-change="checkIfFormShouldbeValidated()" ng-model="item.name"></select>
// Inside controller
$scope.checkIfFromShouldBeValidated = function(){
if( $scope.item.name == 4th Item ) $scope.shouldValidate = true;
else $scope.shouldValidate = false;
};
$scope.formSubmit = function(){
if(($scope.shouldValidate && form.$valid) || (!$scope.shouldValidate)){
// Submit Form
}
};
See if it helps.
I wrote this recursive function inside my controller to check the validity of all child scopes.
function allValid(scope) {
var valid = true;
if (scope.$$childHead) {
valid = valid && allValid(scope.$$childHead);
}
if (scope.$$nextSibling) {
valid = valid && allValid(scope.$$nextSibling);
}
if (scope.scorePlannerForm) {
valid = valid && scope.myForm.$valid;
}
return valid;
}
Then in my controller I check this with the controller scope.
function formSubmit() {
if (allValid($scope)) {
// perform save
}
}

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'print_ad_option_id'

So I have method in which I do some ajax:
function prodChange() {
console.log(this.value);
// ajax
var url = '#Url.Action("GetAdvProdList", "Contract")' + '?prod_id=' + this.value;
$.ajax({
url: url,
type: 'GET',
success: showAdvProd,
error: function() {
console.log("FAILSHAKUREHKGAHH");
}
});
}
The ajax returns successfully and calls this controller method.
public ActionResult GetAdvProdList(int prod_id) { // product id
// get advertising products for this product
OutlookMediaEntities1 db = new OutlookMediaEntities1();
var advsList = from printAdOption in db.print_ad_option
where printAdOption.print_product_id == prod_id
select printAdOption;
List<SelectListItem> adv_list = new List<SelectListItem>(); // list of ads
List<print_ad_option> advs = advsList.ToList(); // list from db
foreach (print_ad_option av in advs)
{
SelectListItem temp_item = new SelectListItem();
temp_item.Text = av.name;
temp_item.Value = av.print_ad_option_id.ToString();
adv_list.Add(temp_item);
}
ViewData["advproducts"] = new SelectList((IEnumerable<SelectListItem>)adv_list.ToList(), "Value", "Text");
return null;
}
I'm returning null because it doesn't work if I return View or PartialView, and I don't think I want it to return those things anyway. All I want is the viewdata stuff to be set.
The ajax worked well before I added code to use the view data. Unfortunately when I try to use the new ViewData in the ajax success method, I get this error:
"There is no ViewData item of type 'IEnumerable' that has the key 'print_ad_option_id'"
The thing is that I get this error when I first load the page, so it seems to be attempting to evaluate the "#Html.DropDownListFor..." before the showAdvProd function is called:
// called when the ajax returns a list of adv prods in a viewdata
function showAdvProd() {
// add drop down
$("#drdn1").append('#Html.DropDownListFor(m => m.print_ad_option_id, ViewData["advproducts"] as SelectList)');
}
The function that does ajax is called when an item is selected from a (different) dropdown menu, but with this error the page doesn't even load, so obviously the ajax function is never called and thus the controller method never called. So of course it won't recognize the viewdata...
I'm similarly creating a dropdown menu in another part of my form, using viewdata but without ajax, and it works fine. So I think something is wrong with my ajax or my controller method, not with how I'm using the viewdata.
Thank you in advance for any help!
The problem is that on your initial page load, the view engine will evaluate all the code blocks - anything with a '#' symbol in front of it. Thus it will try and look for a ViewData item called advproducts before it exists, even though that reference is within a javascript function that hasn't been called yet. Remember - code blocks (such as #Html.blahblahblah() are evaluated server side, while you are expecting your ajax to run on the client side, after the page has been sent to the client.
A couple of options: Returning a partial view should work. You could return a partialview that contains a dropdown and fill it from the ViewBag. That would look like this:
initial page:
...
<div id="advProductsSection"></div>
...
Your ajax would call the same function, but would return a partial view:
public ActionResult GetAdvProdList(int prod_id) { // product id
...
ViewData["advproducts"] = new SelectList((IEnumerable<SelectListItem>)adv_list.ToList(), "Value", "Text");
return View("_AdvProducts");
}
And then a partial view (Here named _AdvProducts.cshtml):
#Html.DropDownList("className", (IEnumerable<SelectListItem>) ViewBag["advproducts"])
Your ajax function would need to change to replace the div with the new partial:
success: function (result) {
$('#advProductsSection').html(result);
}
Or something like that..
A second alternative is to return JSON from the Action Method and populate a dropdown with that.
Your Controller:
...
return JSON(adv_list.ToList());
}
Then in your ajax success func:
success: function(list) {
// states is your JSON array
var $dropdown = $('#Dropdown');
$.each(list, function(i, product) {
$('<option>', {
value: list.Value
}).html(list.Text).appendTo($dropdown);
});
}
You'd need to cleat the dropdown again when prodchange is called.

Dynamically load Partial Views

How can i dynamically load a Partial View?
I mean I have this view, lets say ListProducts, there I select some dropdownlists with products, etc, and with the selected values from those I wanna fill a partial view, which would be in a div that was invisible but after onchange() event would become visible and with the data from the specific selected items.
Use jQuery's $.load() with a controller action that returns a partial view.
For example:
HTML
<script type="text/javascript">
$(document).ready(function()
{
$("#yourselect").onchange(function()
{
// Home is your controller, Index is your action name
$("#yourdiv").load("#Url.Action("Index","Home")", { 'id' : '123' },
function (response, status, xhr)
{
if (status == "error")
{
alert("An error occurred while loading the results.");
}
});
});
});
</script>
<div id="yourdiv">
</div>
Controller
public virtual ActionResult Index(string id)
{
var myModel = GetSomeData();
return Partial(myModel);
}
View
#model IEnumerable<YourObjects>
#if (Model == null || Model.Count() == 0)
{
<p>No results found</p>
}
else
{
<ul>
#foreach (YourObjects myobject in Model)
{
<li>#myObject.Name</li>
}
</ul>
}
You can do this by following these steps. In your controller, you return a partial view.
[HttpGet]
public virtual ActionResult LoadPartialViewDynamically()
{
var query = _repository.GetQuery();
return PartialView("_PartialViewName", query);
}
then in the view you have an empty div
<div id="partialgoeshere"></div>
and then load the partial view using jQuery:
function LoadPartialView() {
$.get("#Url.Action(MVC.ControllerName.LoadPartialViewDynamically())", { null }, function (data) {
$("#partialgoeshere").empty();
$("#partialgoeshere").html(data);
});
}
Hope this helps
I believe you can do something like this example, just using the change event on your dropdown instead. It's a simple jQuery call, you can find more on the jQuery website.
$("#dropdown").change(function() {
$("#destination").load("/Products/GetProduct", $(this).val(),
function(result) {
// do what you need to do
});
});
The first parameter is the view you need to call for the details.
The second parameter is the selected value.
The third parameter of the $.load function is the callback function, where you can parse the result and do what you need to do.
If you have a multiple select $(this).val() that will give you an array with the selected options.
If you want only return a Json object you may want to follow this example.
Use Ajax :)
http://api.jquery.com/jQuery.ajax/
Example:
$.post(window.gRootPath + "Customer/PartialView", { Question: questionId})
.done(function (data) {
$('#partialDiv').html(data.responceText);
});
You can use ajax to call action an then just insert html string using jQuery to the page where you want it to appear:
Server-side:
Render partial view to string
Renders partial view on server to html string, useful when you need to add partial view to ASP.NET MVC page via AJAX.
Client-side:
$('#yourDdl').change(function()
{
$.get('/InsertPartialViewUsingAjax', function (data)
{
$('#container').html(data);
});
});
The following article tells you how to do it with minimum javascript. Basically you return html instead of JSON to your response object.
https://www.simple-talk.com/content/article.aspx?article=2118

Passing strongly type form model data in asp.net mvc through jquery

It is easy to submit form to an action method in the controller which has strongly typed textboxes for example, with a submit button, but what if I want to send the exact same form with the strongly typed textboxes through jquery perhaps the $.ajax call after something else has been clicked.
code like this:
#Html.TextBoxFor(m => m.topTenFav.YoutubeLink,new { id="youTubeLinkTxt"})
does all the work for us and it's very simple to map the properties of our object in the controller
[HttpPost]
public ActionResult AddTopTenFav(HomeViewModel topTen)
{
topTen.topTenFav.Date = DateTime.Now;
topTen.topTenFav.UserName = User.Identity.Name;
repository.AddTopTen(topTen);
repository.Save();
return RedirectToAction("Index");
}
How would I send this form to the controller, map the textboxes in the form to object's properties on a click event such as
$("#btnAddGenre").click(function () {}
#using (Html.BeginForm(
"AddTopTenFav", "Home", FormMethod.Post, new { id = "AddTopTenFavForm" }))
{
<span id="youTubeLinkSpan">Youtube Link</span>
<div>
#Html.TextBoxFor(m => m.topTenFav.YoutubeLink,new { id="youTubeLinkTxt"})
</div>
<span id="youTubeNameSpan">Song Title</span>
<div>
#Html.TextBoxFor(m => m.topTenFav.Title,new { id="youTubeNameTxt"})
</div>
<button type="submit" name="btnSubmit" value="">submit</button>
}
You can do the following post:
$(document).ready(function(){
$('#btnAddGenre').click(function () {
$.post(
$('#AddTopTenFavForm').attr('action'),
$('#AddTopTenFavForm').serialize,
function (data) {
window.location = #Url.Action("Index");
},
'html' // returned data type
);
});
});
I use the html data type so you can return whatever you want and the redirect occurs on the window.location using the #Url.Action to give the location.
Please if it work mark as accepted answer
yes you can post the data of strongly typed textboxex using jquery.
First you have to do
take the values of all the textboxex in jquery using the below code.
var xx= $("#xx").val();
this will give the val in xx from your mvc text box.
Then by using jquery ajax call you can call the action method.
the code is below.
$.get("/XXXX/YY/1", { xxName: xx }, function (data) {
var status = data;
alert(status);
if (status) {
return true;
}
else {
alert("The book with this name is already present. TRY DIFFERENT NAME!")
return false;
}
});
here xxxx is controller amd yy is action method name.the next parameter is the value of all the textboxes which you want to send as an parameter.
This will perform the ajax call and return the value.
Please tell me if you find any problem the i will give the whole code.

dojo dijit client side validation onchange

So I followed the example in the Dojo - Using the Dojo JavaScript Library to Build Ajax Applications to add server-side validation to the username validationtextbox field on my form. Basically I added a usernameOnChange function that submitted an xhrGet request, the xhrGet returns JSON and is handled by the usernameValidationHandler.
It works great, but the usernameValidationHandler only sets the tooltip display message to an error. It doesn't set the field to be invalid and thus the user can still submit the form. How do I set the field to be invalid so the form won't submit?
<input type="text" id="userName" name="userName" size="20"
dojoType="dijit.form.ValidationTextBox"
trim="true"
required="true"
onChange="userNameOnChange"
regExp="\w+"
invalidMessage="User name is required"
/>
function userNameOnChange() {
var userName = dijit.byId("userName").getValue();
if (userName == "") {
return;
}
dojo.xhrGet( {
url: "validateUserName.jsp?userName=" + userName,
handleAs: "json",
handle: userNameValidationHandler
});
}
function userNameValidationHandler(response) {
dijit.byId("userName").displayMessage();
if (!response.valid) {
var errorMessage = "User name already taken";
// Display error message as tooltip next to field
dijit.byId("userName").displayMessage(errorMessage);
// HOW DO I SET THE FIELD TO BE INVALID NOW???
}
}
It seems I was having the same issues when I used the validation method (validator) for the control. I think the issue is with the nature of the xhrGet method as it is asychronous, so the method for determining if value is valid returns before the query is complete. Anyways, this is what I did to get it working. If there is another way, hopefully someone can post.
dojo.require("dijit.form.ValidationTextBox");
function validateUsername(value, constraint) {
// I believe the whole reason you have to hack at control to get it to
// display an error is due to the nature of the xhrGet call. Since the
// call is being made asychronously, the method would have already
// returned a result to the html control before query has finished.
// Therefore you have to do the extra method calls below. Also note
// that when the form goes for submission, it calls each controls validator
// method again! Meaning it will query the webpage again.
var loginID = dijit.byId("user_login");
var bNoNameFound = ("Error" == loginID.get("state")) ? false : true;
if ("" == loginID.value) {
// for some required=true is not kicking in, so we are forcing it.
bNoNameFound = false;
} else {
if (false == loginID._focused) {
console.log("Checking username...");
dojo.xhrGet({
url: "functions/does_user_exist.php?user_login=" + value,
handleAs: 'text',
content: {
l: value
},
timeout: 10000,
load: function(data) {
if (1 == data) {
// setting the state to error since the username is already taken
bNoNameFound = false;
loginID.set("state", "Error");
loginID.displayMessage("The username is already taken...");
// used to change the style of the control to represent a error
loginID._setStateClass();
console.log("Invalid username");
} else {
bNoNameFound = true;
loginID.set("state", "");
loginID.displayMessage("");
}
}
});
}
}
return bNoNameFound;
}
<input dojoType="dijit.form.ValidationTextBox" type="text" name="user_login" id="user_login" value="" minSize="1" maxSize="25" tabindex="10" required="true" trim="true" regExp="\w+" validator=validateUsername />
Note: I also tried using "sync" in the xhrGet parameters as well. It also had issues (aside from the obvious of locking the control until query is done)...
You could subclass the widget to override the validator method. Perhaps chain up, if you want the base functionality, then, if the result is true, run your own test with the getXhr and return the result.
An example at dojocampus just clobbers the validator method. That might also work, depending on what you want to do.

Resources