passing drop downlist selected value to Ajax.ActionLink - asp.net-mvc-3

i have a dropdown list in my view which is populated through model . i want to pass the selected value to
ajax link.
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >
#item.cname</option>
}
</select>
#Ajax.ActionLink("Submit", "Someaction" , new { id = } , new AjaxOptions { UpdateTargetId = "result" })
<div id="result"></div>
how should i route selected value of dropdown ? please help

Selected change action is the client side event, so you cannot handle this event with helpers. But you can use somethink like this:
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >#item.cname</option>
}
</select>
script
$("#dd").change(function() {
var selectedVal = $(this).val();
// in here you have ddl value
// you can pass this parameter with
// ajax and update your result div
$.ajax({
url : 'Home/SomeAction',
data : { selected : selectedValue },
...
success : function(result){
$("#result").html(result);
}
});
});
controller
public ActionResult SomeAction(int selected)
{
// selected is the selected value of DDL...
//return Json/PartialView
}

Related

How do I set selected value that is base on drop-down list in Jquery and assign it to my model?

I need the value from the option to be assigned to my model once the user clicks on the specific option.
<select name="isEmailVerified" class="form-select">
<option value="" selected> all </option>
<option value="true"> verified </option>
<option value="false"> unverified </option>
</select>
expected value => #Model.IsEmailVerified.XXXXX(my value)
What I usually do when I want to asyncronously send data back and forth is this:
I take advantage of Tag Helpers as they're great and saves you a ton of boilerplate code, so I create a standard <form> element without an actual Submit button, just a div that looks like one. You might want to check official MSDN Documentation for the Select Tag Helper to create an appropriate model.
#model VerificationModel
<form asp-action="CheckEmail" method="post">
<select asp-for="IsEmailVerified" asp-items="Model.VerificationTypes">
<div id="SubmitCheck" class="btn">Check email</div>
</form>
Create a javascript function that takes care of the actual submitting chore. Since the form is created with the Tag Helpers, the request body will automatically bind
$('#SubmitCheck').on('click', function() {
let form = $(this).parents('form')[0];
let formData = new FormData(form);
let request = function () {
return fetch(form.getAttribute('action'), {
method: 'POST',
body: formData
});
};
let onresponse = function() {
// do some preliminary actions on 200 response
}
let callback = function() {
// deal with response result
}
let onerror = function() {
// deal with errors
}
request()
.then(response => onresponse())
.then(result => callback())
.fail(err => onerror());
})
Add the [FromForm] attribute to Controller props (model is the same used in the page) to ensure model binding
public async Task<CustomResultClass> CheckEmail([FromForm] VerificationModel model)
{
// do something
}

nested partial View calling HttpPost method 2 times

I have seen this question being asked few times here , but solution I saw are not generic , they are related to their specific code ..
I need to rectify the Work done by previous developer , the flow of ajax calls are wrong in code
In my Situation I have views like :
1.Index (Main View)
2.ParentCategoryList (partial View inside Index)
3. AddChild (partial View inside ParentCategoryList )
4. childCategorytree (Seperate View )
Problem is that from 2nd nested View (AddChild ) , whhen i click on save button ,httpost method is calling twice
My Index View
<div>
<div class="content" id="divparent">
</div>
<div class="content" id="dvChild">
</div>
</div>
its script
#section scripts{
<script type="text/javascript">
$('document').ready(function () {
//------------
$.get('#Url.Action("ParentCategoryList", "List")', function (data) {
$("#divparent").html("");
$("#divparent").html(data);
});
})
function addnewchild(url) {
$.get(url, function (data) {
$("#dvChild").html("");
$("#dvChild").html(data);
});
}
</script>
}
First Partial View inside Index (ParentCategoryList.cshtml)
#foreach (Bmsa.UI.Models.ListsResultModel data in Model)
{
<tr> <td><a onclick="addnewchild('#Url.Action("AddChild",
"List", new { id = #data.listID })')" >
</a> </td></tr> } </tbody> </table>
2nd Nested Partial View inside ParentCategoryList
#using (Ajax.BeginForm("AddChild", "List", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dvChild"
}))
{
<div > <input type="submit" value="Save" /></p></div>}
and Controller methods
public ActionResult ParentCategoryList()
{
//Code
return PartialView("ParentCategoryList", categoryList); }
//GET Operation to Load this View
public ActionResult AddChild(int id)
{
ViewBag.ParentID = id;
ListsAddModel addchild = new ListsAddModel();
addchild.parentListId = id;
return PartialView("AddChild", addchild);
}
[HttpPost] (**this method is calling twice--this is the problem** )
public ActionResult AddChild(ListsAddModel model,int id)
{
//Code
return RedirectToAction ("ChildCategoryListTree", new { id = model.parentListId });
}
and childCategorytree Partial view (also blank one)
I am not able to prevent this method to called twice . I tried e.preventDefault() in $.ajax call , but it is not working ...
I have tried to minimise the code , I think the problem is in RedirectToAction , but I am not sure
Any Help would be appreciated

How to show value inside input filed on change of drop down value using zend framework 2

I am trying to create an onchange event in zend framework 2. suppose if i change option form dropdown list then the related value will be shown on input field .Here my dropdown works fine .but when i am trying to change dropdown list then there is no value shows on my input field.but the data comes.but not display on broweser.So tell me how it is possible.
Here is My Controller
public function propratingAction()
{
$projectName = $this->propinquity()->projectName();
if($this->getRequest()->isPost())
{
$project =$this->getRequest()->getPost('project');
$projectD = json_decode($project, true);
//print_r($projectD);
$propinquityindex=$this->propinquity()->getproprating($projectD);
$propratingHTML=$this->propratingHTML($propinquityindex);
print_r($propratingHTML);
}
$viewModel = new ViewModel();
$viewModel->setVariables(array('key' => 'value'))
->setTerminal(true);
return $viewModel;
}
public function propratingHTML($propinquityindex){
$html='';
foreach ($propinquityindex as $value) {
# code...
$html .='<input type="text" value="'.$value['critics_rating'].'"/>';
}
print_r($html);
$viewModel = new ViewModel();
$viewModel->setVariables(array("key" => "value"))
->setTerminal(true);
return $viewModel;
}
Here is view part
<div style="display:inline-block; margin-left:55px; margin-top:20px;">
<select style="width:12.5em;" id="project_id" onchange="getsectorindexAjax();"
data-placeholder="Project Name" class="selectError2" data-rel="chosen"
name="project_id" >
<option value="">--select project--</option>
<?php if($this->projectName){
foreach($this->projectName as $val){
echo '<option value="'.$val['project_id'].'">'.$val['Project_name'].'
</option>';
}
} ?>
</select>
</div>
<div class="main" style="display:inline-block; margin-left:10px;margin-top:20px;">
CRc Rating
<input style="width:20em;height:2.7em;" name="critics_rating"
id="critics_rating" type="text" value="">
</div>
ajax call
function getsectorindexAjax()
{
require(["dojo/request", "dojo/query","dijit/registry"], function(request, registry) {
// Locate the JS object.
var project = dojo.byId("project_id").value;
//alert(project);
request.post("http://localhost/admin/propinquity/proprating",{
data : {
project : JSON.stringify(project)
}
}).then(function(text) {
dojo.byId("critics_rating").innerHTML = text;
console.log("return data : " + text);
});
});
}
So suggest me how can i show value inside input field when my dropdown value is change.
You can try something like this :
var dropdown= dijit.byId("project_id"); //get the select element
//on change event
dropdown.on('change', function(evt) {
//get the selected value
var project = dropdown.get("value");
//your ajax request
request.post("http://localhost/admin/propinquity/proprating",{
data : {
project : JSON.stringify(project)
}
}).then(function(text) {
dijit.byId("critics_rating").attr("value", text);
console.log("return data : " + text);
});
});

How to Add update panel in MVC 3

I am updating product Quantity by Update button, after clicking on update button page is reloading, instead of reloading that page i want to update that "cartUpdatePanel" table area only by Ajax
My View is
using (Html.BeginRouteForm("ShoppingCart", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table id="cartUpdatePanel" class="table_class" cellpadding="0" cellspacing="0">
#foreach (var item in Model.Items)
{
<tr style="background: #f3f3f3;">
<td>
<input type="submit" name="updatecartproduct#(item.Id)" value="Update Cart" id="updatecartproduct#(item.Id)" />
</td>
</tr>
}
}
My Controller action is, by which i am updating Product Quantity
[ValidateInput(false)]
[HttpPost, ActionName("Cart")]
[FormValueRequired(FormValueRequirement.StartsWith, "updatecartproduct")]
public ActionResult UpdateCartProduct(FormCollection form)
{
if (!_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart))
return RedirectToRoute("HomePage");
//get shopping cart item identifier
int sciId = 0;
foreach (var formValue in form.AllKeys)
if (formValue.StartsWith("updatecartproduct", StringComparison.InvariantCultureIgnoreCase))
{
sciId = Convert.ToInt32(formValue.Substring("updatecartproduct".Length));
break;
}
//get shopping cart item
var cart = _workContext.CurrentCustomer.ShoppingCartItems
.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
var sci = cart.Where(x => x.Id == sciId).FirstOrDefault();
if (sci == null)
{
return RedirectToRoute("ShoppingCart");
}
//update the cart item
var warnings = new List<string>();
foreach (string formKey in form.AllKeys)
if (formKey.Equals(string.Format("itemquantity{0}", sci.Id), StringComparison.InvariantCultureIgnoreCase))
{
int newQuantity = sci.Quantity;
if (int.TryParse(form[formKey], out newQuantity))
{
warnings.AddRange(_shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
sci.Id, newQuantity, true));
}
break;
}
//updated cart
cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
var model = PrepareShoppingCartModel(new ShoppingCartModel(), cart, true, false, true);
//update current warnings
//find model
var sciModel = model.Items.Where(x => x.Id == sciId).FirstOrDefault();
if (sciModel != null)
foreach (var w in warnings)
if (!sciModel.Warnings.Contains(w))
sciModel.Warnings.Add(w);
return View(model);
}
How i will achieve to update "cartUpdatePanel" table area after clicking on update button by ajax
Thanx in Advance
Please consider using Ajax.BeginForm helper to create the form. You can use AjaxOptions to specify callback code to capture server output and do whatever you want (including injecting it to a div, table, field set ..)
Using the Ajax.BeginForm is very easy
#using (Ajax.BeginForm(
"name_of_the_action",
new AjaxOptions {
OnSuccess = "processServerResp",
HttpMethod = "POST"},
new {enctype="multipart/form-data"})
){
// rest of the form code
}
Now using javascript, implement processServerResp as a function which takes a single parameter. This parameter will contain what ever values passed from the server to the client. Assuming the server is returning html, you can use the following code to inject it into a container with the id of id_fo_the_div
function processServerResp(serverData){
$(‘#id_fo_the_div’).html(serverData);
// or inject into a table ..
}
You can tap into other interesting features provided by AjaxOptions and do very interesting things.
A good article on Ahax.BeginForm http://www.blackbeltcoder.com/Articles/script/using-ajax-beginform-with-asp-net-mvc
Happy coding

Set div id dyanmically in each item in the loop to be referred in Ajax.ActionLink method?

Do we have better ways to handle it?
#foreach (var item in Model)
{
<div id="divDetail#{#item.CategoryId}"/>
#Ajax.ActionLink(
item.CategoryName,
"GetDetails",
new { id = item.CategoryId },
new AjaxOptions() { UpdateTargetId = string.Format("divDetail{0}", item.CategoryId) })
}
</div>
}
I would use the HTML.ActionLink helper method to generate the link and then use my custom jQuery ajax call to get the data. The advantage of doing this is i have full control so that i can do some manipulation of the response data before showing in the detail div.
I added a CSS class to the link so that i can be more specific (in selection of element) when binding my functionality.
#foreach (var item in Model)
{
<div id='divDetail#(item.ID)'></div>
#Html.ActionLink(item.CategoryName, "GetDetails", new { #id = item.CategoryId}, new {#id= "link-"+item.CategoryId, #class="lnkItem" })
}
and the script is
<script type="text/javascript">
$(function () {
$(".lnkItem").click(function (e) {
e.preventDefault();
var itemId = $(this).attr("id").split("-")[1]
$.get($(this).attr("href"), { id: itemId }, function (data) {
//i am free to do anything here before showing the data !
$("#divDetail" + itemId).html(data);
})
});
});
</script>

Resources