how to embed telerik dropdown in telerik gridview - asp.net-mvc-3

I am using telerik controls in my project. How to embed telerik dropdown in telerik grid view with an example project mvc3+razor(cshtml) and controller code is c#?

From Controller just using a TempData or ViewBag to pass data to the View.
List<AdjustmentReasonCodes> salesAuditReasons = new List<AdjustmentReasonCodes>();
salesAuditReasons = salesDal.SalesAuditResonCodes();
TempData["SalesAuditReason"] = salesAuditReasons;
TempData["CStatus"] = salesDal.ReadCustomerListWithRecoveryStatus(objLoginHelper.LogInForUnitCode, Convert.ToByte(ctype), Helper.DateTo(Helper.YearMonthPrevious(2)));
Now just use a list to the view page to hold the TempData
#{
List<AdjustmentReasonCodes> salesAuditReasons = new List<AdjustmentReasonCodes>();
salesAuditReasons = (List<AdjustmentReasonCodes>)TempData["SalesAuditReason"];
}
You can add Combo-box very easy using Template.
<div class="DataGridXScroll">
#{
List<GetCustomerListWithRecoveryStatus> listCustomerStatus = new List<GetCustomerListWithRecoveryStatus>();
listCustomerStatus = (List<GetCustomerListWithRecoveryStatus>)TempData["CStatus"];
if (listCustomerStatus != null)
{
#(Html.Telerik().Grid(listCustomerStatus)
.Name("grvSalesAdjustment")
.DataKeys(keys => keys.Add(k => k.CustCode))
.Columns(column =>
{
column.Bound(a => a.CustCode).Width(100).HtmlAttributes(new { #class = "GridColumnLeftAlign" }).Title("Customer ID");
column.Template(#<input type="text" class="GridTextBoxRightAlign" style="width:62px;" id="#("salesAudit" + #item.CustCode.Replace(" ", "").Replace("-", "").Trim())" value="#(#item.AuditAdjustmentWithoutDPInCurrentMonth.ToString("0"))" />).Title("Audit Adjustment").Width(80);
column.Template(#<select id="#("ddlSalesAuditReason" + #item.CustCode.Replace(" ", "").Replace("-", "").Trim())" class="DropDown">
<option value="0">--Select--</option>
#foreach (AdjustmentReasonCodes adrc in salesAuditReasons)
{
if (item.RefReasonForAuditAdjustment == adrc.ReasonCode)
{
<option value="#(adrc.ReasonCode)" selected="selected">#adrc.ReasonDescription</option>
}
else
{
<option value="#(adrc.ReasonCode)">#adrc.ReasonDescription</option>
}
}
</select>).Title("Audit Reason").Width(135);
}).Selectable()
.Pageable(page => page.PageSize(100))
.Scrollable(scroll => scroll.Height(300))
)
}
}
</div>

Related

How can I set selected model with list?

In my controller I set the items in the ViewBag:
List<ShopItemModel> items = new List<ShopItemModel>();
/* populate my items */
ViewBag.Items = items;
So on the cshtml i run thru the list, but how do I connect it so on postback sets the argument of the Post method in the controller?
The CSHTML:
#model Models.ShopItemModel
<h2>Webshop</h2>
#foreach( var item in ViewBag.Items)
{
using (Html.BeginForm())
{
<p>#item.Name</p> <!-- List the item name, but not bounded? -->
#Html.LabelFor(model => model.Name, new { Name = item.Name }) <!-- outputs just "Name", not the items name -->
<input type="submit" value="Buy" />
}
}
The post version of the method in the controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(ShopItemModel m)
{
return View();
}
But how do I fix this binding? So I fetch the selected item from the list?
In your view:
using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
#Html.LabelFor(model => model[i].Name)
}
}
This will produce html controls like this:
<input name="ShopItemModel[3].Name" ...
If you're using this in a form, in your controller, iterate over the POSTed model data:
foreach (var item in model)
{
... do something to each item
}
You can use a foreach loop in the view rather than a for loop, example here

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 can I make my SelectListItem overload set the “Value” property to be the same as the “Text” property?

I’am tryinng to do something like this in my view:
#{
string selectgedOne = ViewBag.sellectedvalue;
}
#Html.DropDownListFor(x => x.Category, Model.Categories.Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString(), Selected = x.ToString().Equals(selectgedOne.ToString()) }))
But what returns is...
System.Web.Mvc.SelectListItem
I’m sort of successful whin I use this version …
#Html.DropDownListFor(x => x.Category, Model.Categories, selectgedOne)
…here it sets the value in the list box but when I F12 the page I see that first option value is not set to the same as the text…
<select id="Category" name="Category">
<option value="">Tests</option>
<option value="In class participation">In class participation</option>
<option value="Homework">Homework</option>
<option value="Projects">Projects</option>
<option value="Tests">Tests</option>
<option value="Other">Other</option>
</select>
… so if I post this to the controller Categary will be a empty string.
How can I make my SelectListItem overload set the “Value” property to be the same as the “Text” property?
Thanks for helping.
I sent the value (assignCategory) that I want at the top of the list then...
public ActionResult Categories(int? id, int? department, String assignCategory)
{
var categories = new List<SelectListItem>();
for (int i = 0; i < rubricsList.Count(); i++)
{
categories.Add(new SelectListItem
{
Text = rubricsList[i],
Value = rubricsList[i],
Selected = true
});
}
switch (assignCategory)
{
case "A":
categories.Insert(0, new SelectListItem
{
Text = rubricsList[0],
Value = rubricsList[0],
Selected = true
});
break;
// More cases here
}
The return view is partial with a single line that looks like this:
#Html.DropDownListFor(x => x.Category, Model.Categories)
Now the first value in the dropdown list is set and can be submitted properly

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

passing drop downlist selected value to Ajax.ActionLink

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
}

Resources