how will I call the on change event of the ajax dropdownlist? - ajax

In my MVC application I am using an ajax dropdownlist and an ajax Cascading dropdownlist I want to write the onChange event of the cascading dropdownlist please tell me what shall I do.
I am posting the view page that I am using and the js file that creates the cascading dropdownlist.Please tell me where all the places I need to do the changes.
The view Page is as follows
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index1</title>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
<script type="text/javascript" src="../../Scripts/CascadingDropDownList.js"></script>
</head>
<body>
<div>
<label for="Makes">Car Make:</label>
<%= Html.DropDownList("Makes")%>
<label for="Makes">Car Model:</label>
<%= Html.CascadingDropDownList("Models", "Makes")%>
<br />
<%=Html.TextBox ("id",ViewData ["id"]) %>
</div>
</body>
</html>
The javascript where the cascading dropdown list is being formed:
public static class JavaScriptExtensions
{
public static string CascadingDropDownList(this HtmlHelper helper, string name, string associatedDropDownList)
{
var sb = new StringBuilder();
// render select tag
sb.AppendFormat("<select name='{0}' id='{0}'></select>", name);
sb.AppendLine();
// render data array
sb.AppendLine("<script type='text/javascript'>");
var data = (CascadingSelectList)helper.ViewDataContainer.ViewData[name];
var listItems = data.GetListItems();
var colArray = new List<string>();
foreach (var item in listItems)
colArray.Add(String.Format("{{key:'{0}',value:'{1}',text:'{2}'}}", item.Key, item.Value, item.Text));
var jsArray = String.Join(",", colArray.ToArray());
sb.AppendFormat("$get('{0}').allOptions=[{1}];", name, jsArray);
sb.AppendLine();
sb.AppendFormat("$addHandler($get('{0}'), 'change', Function.createCallback(bindDropDownList, $get('{1}')));", associatedDropDownList, name);
sb.AppendLine();
sb.AppendLine("</script>");
return sb.ToString();
}
}
public class CascadingSelectList
{
private IEnumerable _items;
private string _dataKeyField;
private string _dataValueField;
private string _dataTextField;
public CascadingSelectList(IEnumerable items, string dataKeyField, string dataValueField, string dataTextField)
{
_items = items;
_dataKeyField = dataKeyField;
_dataValueField = dataValueField;
_dataTextField = dataTextField;
}
public List<CascadingListItem> GetListItems()
{
var listItems = new List<CascadingListItem>();
foreach (var item in _items)
{
var key = DataBinder.GetPropertyValue(item, _dataKeyField).ToString();
var value = DataBinder.GetPropertyValue(item, _dataValueField).ToString();
var text = DataBinder.GetPropertyValue(item, _dataTextField).ToString();
listItems.Add(new CascadingListItem(key, value, text));
}
return listItems;
}
}
public class CascadingListItem
{
public CascadingListItem(string key, string value, string text)
{
this.Key = key;
this.Value = value;
this.Text = text;
}
public string Key { get; set; }
public string Value { get; set; }
public string Text { get; set; }
}

You should register the control during the application initialization. It's what you have to render in the page via CascadingDropDownList extension method.
Sys.Application.add_init(function() {
$create(NameSpace.ClassName, null, null, null, $get("id"));
});
Type.registerNamespace("NameSpace");
NameSpace.ClassName = function(element) {
NameSpace.ClassName.initializeBase(this, [element]);
}
NameSpace.ClassName.prototype = {
initialize: function() {
NameSpace.ClassName.callBaseMethod(this, "initialize");
$addHandler(this.get_element(), "change", Function.createDelegate(this, onChange));
},
dispose: function() {
NameSpace.ClassName.callBaseMethod(this, "dispose");
$removeHandler(this.get_element(), "change", Function.createDelegate(this, onChange));
},
onChange: function() {
// Do somethings...
}
}
NameSpace.ClassName.registerClass(NameSpace.ClassName, Sys.UI.Control);
The above code snippet illustrates how to add an handler for change event.

Related

View not updating when model changed

I have a single page UI, which looks like below .
on the UI there are two checkboxes, when user toggle the states of checkbox, I use ajax to post the status to HomeController in a POST action.
after updated the model in POST action with the new checkboxes states, I redirect back to GET action to return a view.
however, the UI does not refresh with the new model.
can someone help on this ? thanks.
Views/Home/Index.cshtml
#{
Layout = "_Layout";
}
#model WebApplication5.Controllers.HomeModel;
<h1>STS</h1>
<div>
<input type="checkbox" id="UseVersionCheckBox" />Use version v1 in url
</div>
<br />
<div>
<input type="checkbox" id="ResponseTypeTokenCheckBox" /> Return access token in url
</div>
<div>your check status : #Model.IsChecked</div>
<br />
<div>your text : #Model.Text </div>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - WebApplication5</title>
</head>
<body>
#RenderBody()
<script src="~/jquery-2.1.0.min.js"></script>
#RenderSection("Scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
function fun() {
var current = $("#UseVersionCheckBox").prop("checked");
var current2 = $("#ResponseTypeTokenCheckBox").prop("checked");
alert("values as:" + current + "," + current2);
var json = {};
json.UseVersionChecked = current;
json.ResponseTypeTokenChecked = current2;
var text = JSON.stringify(json);
$.ajax({
type: "POST",
url: "Home/Index",
data: text,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (r, s, e) {
},
success: function (r) {
},
complete: function () {
}
});
}
$("#UseVersionCheckBox").click(fun);
$("#ResponseTypeTokenCheckBox").click(fun);
});
</script>
</body>
</html>
HomeController.cs
public class HomeController : Controller
{
public HomeController()
{
}
public IActionResult Index()
{
HomeModel model;
if (TempData.ContainsKey("model"))
{
var newmodel = JsonConvert.DeserializeObject<HomeModel>(TempData["model"].ToString());
model = newmodel;
}
else
{
model = new HomeModel();
model.IsChecked = false;
model.Text = "not checked";
}
ModelState.Clear();
return View(model);
}
[HttpPost]
public IActionResult Index([FromBody] CheckStatus status)
{
HomeModel model = new HomeModel();
model.IsChecked = true;
model.Text = "UseVersionCheckBox : " + status.UseVersionChecked + " ; ResponseTypeTokenCheckbox : " + status.ResponseTypeTokenChecked;
if (TempData.ContainsKey("model"))
TempData.Remove("model");
TempData.Add("model", JsonConvert.SerializeObject(model));
ModelState.Clear();
return RedirectToAction("Index", "Home");
}
}
[Serializable]
public class HomeModel
{
public bool IsChecked { get; set; }
public string Text { get; set; }
}
public class CheckStatus
{
public bool UseVersionChecked { get; set; }
public bool ResponseTypeTokenChecked { get; set; }
}
weird thing , after checked the response of redirect to GET action, the new value is there ,but web page in browser still show old. why ?

How to get selected Drop down list value in view part of MVC?

I want to pass selected Drop down list value to Ajax Action Link which is I am using in Controller. Every time When I will change drop down list value. I want that respective value pass to the action link.
What I need to write here in Ajax Action Link ????
Drop Down List
<div class="form-group">
#Html.DropDownListFor(model => model.ComponentId, ((List<string>)ViewBag.Cdll).Select(model => new SelectListItem { Text = model, Value = model }), " -----Select Id----- ", new { onchange = "Action(this.value);", #class = "form-control" })
</div>
Ajax Action Link
<div data-toggle="collapse">
#Ajax.ActionLink("Accessory List", "_AccessoryList", new { ComponentId = ???? }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divacc",
InsertionMode = InsertionMode.Replace
})
</div>
Controller
public PartialViewResult _AccessoryList(string ComponentId)
{
List<ComponentModule> li = new List<ComponentModule>();
// Code
return PartialView("_AccessoryList", li);
}
Here is a new post. I do dropdowns a little different than you, so I am showing you how I do it. When you ask what to pass, I am showing you how to pass the dropdown for 'component' being passed. I also show how to pass from ajax back to the page.
Controller/Model:
//You can put this in a model folder
public class ViewModel
{
public ViewModel()
{
ComponentList = new List<SelectListItem>();
SelectListItem sli = new SelectListItem { Text = "component1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "component2", Value = "2" };
ComponentList.Add(sli);
ComponentList.Add(sli2);
}
public List<SelectListItem> ComponentList { get; set; }
public int ComponentId { get; set; }
}
public class PassDDLView
{
public string ddlValue { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostDDL(PassDDLView passDDLView)
{
//put a breakpoint here to see the ddl value in passDDLView
ViewModel vm = new ViewModel();
return Json(new
{
Component = "AComponent"
}
, #"application/json");
}
public ActionResult IndexValid8()
{
ViewModel vm = new ViewModel();
return View(vm);
}
View:
#model Testy20161006.Controllers.ViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid8</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function () {
var PassDDLView = { ddlValue: $("#passThis").val() };
$.ajax({
url: '#Url.Action("PostDDL")',
type: 'POST',
data: PassDDLView,
success: function (result) {
alert(result.Component);
},
error: function (result) {
alert('Error');
}
});
})
})
</script>
</head>
<body>
<div class="form-group">
#Html.DropDownListFor(m => m.ComponentId,
new SelectList(Model.ComponentList, "Value", "Text"), new { id = "passThis" })
<input type="button" id="btnClick" value="submitToAjax" />
</div>
</body>
</html>

How to send Model value as parameter while submitting #Ajax.Beginform()

I am using #Ajax.Beginform in my View which is tightly bound to the ViewModel.
I've #Html.ListBoxFor inside my form. I add and delete items from the listbox using jQuery. Now what I am want to achieve is that onpress of the submit button, it should send full data present in the listbox regardless of which are selected. Currently it sends the list to controller if I select all the item in the listbox and press submit button. But I don't want to do that. Any idea as to how to achieve this?
Can it be sent as a form parameter.
#using (Ajax.BeginForm("SaveTextComponent", "LoanFilterEditor", new{ param1 = Model.listBoxItem}, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SUCCESS" }))
I try to accept the parameter in the controller like this
public ActionResult SaveTextComponent(TextComponentViewModel model, List<SelectListItem> list)
{
}
But list is null.. Please help.
Maybe you can use this javascript to select all items at your listbox and then, send it to controller:
function listbox_selectall(listID, isSelect) {
var listbox = document.getElementById(listID);
for(var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
}
And after that, you can call the function on your form in this way:
<script>
function submit() {
listbox_selectall('righthand_side_listbox_id', true);
return true;
}
</script>
<form onsubmit="return submit()">
...
</form>
Credits to Viral Patel blog
You can follow my example:
Model:
pulic class TextComponentViewModel {
public int[] SelectedListItem { get; set; }
public List<Item> ListItem { get; set; }
}
public class Item {
public int Id { get; set; }
public String Name { get; set; }
}
View:
#model TextComponentViewModel
#using (Ajax.BeginForm("SaveTextComponent", "LoanFilterEditor", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SUCCESS" }, new {name = "mainForm", id = "mainForm"}))
{
#Html.ListBoxFor(model => model.SelectedListItem , new MultiSelectList(Model.ListItem, "ID", "Name"))
for(var i = 0; i < Model.ListItem.Count();i++ )
{
#Html.HiddenFor(m => m.ListItem[i].Id)
#Html.HiddenFor(m => m.ListItem[i].Name)
}
<input type = "submit" id="submitButton" />
}
Controller:
public ActionResult SaveTextComponent(TextComponentViewModel model)
{
}
Script:
$("#submitButton").click(function(){
$("#mainForm").submit();
});

How to Show The image from one view to other view in Asp.Net WebApi MVC4?

HI all i have some images which i am retrieving dynamically and displaying in a view like this
here is my controller
private ProductEntities products = new ProductEntities();
public List<ProductItems> GetAllProducts()
{
var items = new List<ProductItems>();
var records = products.Products.ToList();
foreach (var item in records)
{
ProductItems model = new ProductItems();
model.ProductID = item.ProductId;
model.ProductName = item.ProductName;
model.ImageURL = item.ImageURL;
items.Add(model);
}
return items;
}
and this is my index page view
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductDetails", function (data) {
$.each(data, function (idx, ele) {
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
$("#makeMeScrollable").append('<h4>' + ele.ProductName + '</h4>');
});
});
});
</script>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
</body>
now what i want is when ever an user clicks on a image i have to pass the ID of the image to my method in my apicontroller and i have to display that image in another view ..how do i pass my image to another view and Id to my api/controller action
i have to pass my ProductID to this method
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
return productdeatils ;
}
The thing is that API actions do not return views. They are used to serialize models using some format such as JSON or XML. So when you are saying that you want to use the ProductDeatils API action to display a view, this doesn't make much sense. Views are returned by standard ASP.NET MVC controller actions returning ActionResults. So let's see how to set this up.
Let's suppose that you have the following API controllers:
public class ProductsController : ApiController
{
private ProductEntities products = new ProductEntities();
public IEnumerable<ProductItems> Get()
{
return products.Products.ToList().Select(item => new ProductItems
{
ProductID = item.ProductId,
ProductName = item.ProductName,
ImageURL = item.ImageURL
});
}
}
public class ProductDetailsController : ApiController
{
private ProductEntities products = new ProductEntities();
public ProductItems Get(long id)
{
return products.ExecuteStoreQuery<ProductItems>(
"GetProductDetail #ProductID ",
new SqlParameter("#ProductID", id)
);
}
}
Alright, now we will need standard ASP.NET MVC controller that will serve the views:
public class HomeController : Controller
{
public ActionResult Products()
{
return View();
}
public ActionResult ProductDetail(long id)
{
using (var client = new HttpClient())
{
var productDetailUrl = Url.RouteUrl(
"DefaultApi",
new { httproute = "", controller = "productdetails", id = id },
Request.Url.Scheme
);
var model = client
.GetAsync(productDetailUrl)
.Result
.Content
.ReadAsAsync<ProductItems>()
.Result;
return View(model);
}
}
}
and the respective view for showing the list of products and the detail of a product when a link is clicked:
~/Views/Home/Products.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
<script type="text/javascript" src="~/scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
var productsUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
var productDetailUrl = '#Url.Action("productdetail", "home", new { id = "__id__" })';
$.getJSON(productsUrl, function (data) {
$.each(data, function (idx, product) {
$('<img/>').attr({ src: product.ImageURL }).appendTo('#makeMeScrollable');
$('#makeMeScrollable').append(
$('<h4/>').html(
$('<a/>', {
href: productDetailUrl.replace('__id__', product.ProductID),
text: product.ProductName
})
)
);
});
});
</script>
</body>
</html>
and ~/Views/Home/ProductDetail.cshtml:
#model ProductItems
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ProductDetail</title>
</head>
<body>
<h4>#Html.DisplayFor(x => x.ProductName)</h4>
<img src="#Model.ImageURL">
</body>
</html>

Master-Detail Sample Code for MVC 3 Razor (using Ajax for details)

I am looking for sample code to create a master/details with c# mvc 3.
Specifically, I am trying to figure out how to call via ajax the rendering of a partial view. I am able to put the partial view on the form but want to populate it after a user has selected an item from a select list via ajax.
thx
As always you start with the model:
public class MyViewModel
{
public int Id { get; set; }
public string Title { get; set; }
}
public class DetailsViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: don't hardcode, fetch from repository
var model = Enumerable.Range(1, 10).Select(x => new MyViewModel
{
Id = x,
Title = "item " + x
});
return View(model);
}
public ActionResult Details(int id)
{
// TODO: don't hardcode, fetch from repository
var model = new DetailsViewModel
{
Foo = "foo detail " + id,
Bar = "bar detail " + id
};
return PartialView(model);
}
}
and corresponding views.
~/Views/Home/Index.cshtml:
#model IEnumerable<MyViewModel>
<ul>
#Html.DisplayForModel()
</ul>
<div id="details"></div>
<script type="text/javascript">
$(function () {
$('.detailsLink').click(function () {
$('#details').load(this.href);
return false;
});
});
</script>
~/Views/Home/Details.cshtml:
#model DetailsViewModel
#Model.Foo
#Model.Bar
~/Views/Home/DisplayTemplates/MyViewModel.cshtml:
#model MyViewModel
<li>
#Html.ActionLink(Model.Title, "details", new { id = Model.Id }, new { #class = "detailsLink" })
</li>
I have blogged about creating master detail form using asp.net mvc where you can add n child records on clietn side without the need of sending ajax request just to bring the editor fields for child records. it used jquery templates

Resources