How can i add Autocomplete textbox changed event in MVC3 - asp.net-mvc-3

How can I add an MVC3 autocomplete textbox changed event? Below is my code.
My view code
<div style="float: left">
States Filter :
</div>
<div style="float: left; padding-left: 10px">
#Html.TextBox("Statestxt")
</div>
<div style="padding-left: 10px; float: left">
<input type="image" value="submit" src="../../Images/FilterBrowse.gif"
alt="submit Button" />
</div>
My controller:
public ActionResult AutocompleteAsync(string term)
{
var suggestions = from s in Adm.states
select s.state_name;
var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult States(state stateModel, string _stateName,
FormCollection formvalues)
{
AdmDataContext Adm = new AdmDataContext;
if (Request.Form["Statestxt"] == null)
{
ViewBag.Error = "Enter State Name.";
ViewData["name"] = false;
return View();
}
else
{
_stateName = Request.Form["Statestxt"].ToString();
var record = (from state in Adm.states
where state.state_name == _stateName
select state).Count();
if (record == 0)
{
ViewBag.Error = "Enter Valid State Name.";
return View();
}
var _Stateid = from state in Adm.states
where state.state_name == _stateName
select state;
int StateId = (int)_Stateid.First().state_id;
var state1 = am.FindUpcomingStates2(StateId).ToList();
if (state1 != null)
{
ViewData["name"] = true;
return View("States", state1);
}
}
}
I want to change the data after entering Statestext. Where can I write the code for the Textbox changed event?
Thanks.

I take it you want to call a Javascript function when the user changes the text. There's an overload for the Html.TextBox helper that you can use for this:
#Html.TextBox("Statestxt", "", new { onkeyup = "fnAjaxAutocomplete(this)" })
Then your handler Javascript method would look like this:
function fnAjaxAutocomplete(element)
{
var ajaxUrl = '#Url.Action("AutocompleteAsync")' + '?text=' + element.value;
$.get(ajaxUrl(function(suggestionsJson) {
// handle JSON result here
});
}

Related

how can i get dropdownlist id in controller when we select an item using mvc4

I have dropdownlst which i have filled from database. Now i need to get the selected value in Controller do some manipulation. But null data will get. Code which i have tried.
##View##
#using (Html.BeginForm()) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
}
## Controller ##
public ActionResult ItemPurchased()
{
POS_DBEntities2 db = new POS_DBEntities2();
var query = from i in db.TBL_Account
where i.Type == "supplier"
select i;
ViewBag.PurSupName = new SelectList(query, "AccountId", "AccountName");
return PartialView("ItemPurchased", new List<PurchasedItem>());
}
##Controller##
public ActionResult GetPurchasedItem()
{
var optionsValue = this.Request.Form.Get("SupplierId");
return View();
}
You can try with below changes.
#using (Html.BeginForm("GetPurchasedItem","YourController")) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
<input type="submit" value="OK" />
}
Controller will be
[HttpPost]
public ActionResult GetPurchasedItem(string SupplierId)
{
var optionsValue = SupplierId;
//..............
return View();
}
It should work normally..

How To Populate Html.Listbox with Ajax result using mvc 4

In My MVC 4 App i want to populate Html.LisboxFor with an Ajax result.
My View:
#using (Html.BeginForm("UpdatePriority", "Priority", FormMethod.Post))
{
#Html.Hidden("myListBoxValuesValues")
<div class="row">
<div class="col-md-2">
<label>FA:</label>
#Html.ListBoxFor(m => m.FA, new MultiSelectList(#Model.FA), new { #class = "lbx_FA" })
</div>
<div class="col-md-1">
<input id="btnAdd" type="button" value=" > " onclick="addItem();" />
</div>
<div class="col-md-2">
<label>CEID list:</label>
#Html.ListBoxFor(model => model.CEIDs, new MultiSelectList(Model.CEIDs), new { #class = "lbx_CEIDs" })
</div>
...and so on..
My my controller function (returns string of a json model):
public string getCeidPerFA(string FA)
{
return unitOfWork.ToolRequiredRepository.getCEIDsPerFA_Scenario(DAL.UnitOfWork.Scenario, FA);
}
The repository function:
internal string getCEIDsPerFA_Scenario(string scenario, string FA)
{
//create the result list (FAs):
List<string> FAs = FA.Split(',').ToList();
var CEIDs = from row in context.ToolRequireds
where row.Scenario == scenario && FAs.Contains(row.FA)
select row.CEID;
List<string> lst = CEIDs.Distinct().ToList();
//create Json Result:
List<SelectListItem> items = new List<SelectListItem>();
foreach (var ceid in lst)
{
items.Add(new SelectListItem { Text = ceid, Value = ceid });
}
return Json.Encode(items);
}
My Script:
function addItem() {
var result = "";
var x = document.getElementById("FA");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
result += x.options[i].value + ",";
}
}
result = result.substring(0, result.length - 1);
$.ajax({
url: "#(Url.Action("getCeidPerFA", "CeidSelection"))",
data: { "FA": result },
success: function (data) {
if (data.length > 0) {
JSON.pa
$("#CEIDs").append(JSON.parse(data));
}
else
alert("No Result");
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
My code is wrong but i have no idea how to do so.
Any help will be very appreciated.
loop through the data result like this
$('#CEIDs').empty();
$.each($(data), function(key, value) {
$('#CEIDs').append('<option value=' + key + '>' + value + '</option>');
});

How to open a View in PopUp in MVC 3

I am using MVC 3, in my project i have 2 view, i want to open 2nd view in 1st View popup
My 1st View is by that i want to Open 2nd View in PopUp,
#model CustomerAddressListModel
#using Nop.Web.Models.Customer;
#{
Layout = "~/Views/Shared/_ColumnsTwo.cshtml";
//title
Html.AddTitleParts(T("PageTitle.Account").Text);
}
<script type="text/javascript">
$(function () {
$('a.dialog').click(function () {
var url = $(this).attr('href');
var dialog = $('<div style="display:none"></div>').appendTo('body');
dialog.load(url, {}, function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
close: function (event, ui) {
dialog.remove();
}
});
});
return false;
});
});
</script>
<div class="add-btn-cntrnr left" style="width:400px;">
#Html.ActionLink("AddLink", "AddressAdd", "Customer", new { #class = "dialog" })
</div>
and this is my second view which i want to open in PopUp:
#model CustomerAddressEditModel
#using Nop.Web.Models.Customer;
#{
Layout = null;
}
#using Nop.Web.Framework;
#using (Html.BeginForm())
{
<div class="emai_head">
<span class="emai_head_text">Add Address</span>
#{
var dataDictAddress = new ViewDataDictionary();
//Merge ModelState (required for validation)
dataDictAddress.ModelState.Merge(ViewData.ModelState);
dataDictAddress.TemplateInfo.HtmlFieldPrefix = "Address";
#Html.Partial("_CreateOrUpdateAddress", Model.Address, dataDictAddress)
}
<input type="submit" class="acc_btnn" value=" " />
</div>
}
This is my controller for PopUp view :
[NopHttpsRequirement(SslRequirement.Yes)]
public ActionResult AddressAdd()
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
var model = new CustomerAddressEditModel();
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
model.Address = new AddressModel();
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString() });
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}
[HttpPost]
public ActionResult AddressAdd(CustomerAddressEditModel model)
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
if (ModelState.IsValid)
{
var address = model.Address.ToEntity();
address.CreatedOnUtc = DateTime.UtcNow;
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
customer.Addresses.Add(address);
_customerService.UpdateCustomer(customer);
// return RedirectToRoute("CustomerAddresses");
}
//If we got this far, something failed, redisplay form
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (c.Id == model.Address.CountryId) });
//states
var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value).ToList() : new List<StateProvince>();
if (states.Count > 0)
{
foreach (var s in states)
model.Address.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.Address.StateProvinceId) });
}
else
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}

MVC3 - Asynchronous Pagination

I have a list of objects which uses paging in my home > index.cshtml. When a user clicks through each page of objects I only want to refresh that portion of the page and nothing else. How would I accomplish this?
Ideally I want to use Async Methods and ControllerActions...
Controllers > HomeController.cs
public ViewResult Index(int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
return View(viewModel);
}
Home > Index.cshtml:
#model SportsStore.WebUI.Models.ProductsListViewModel
#{
ViewBag.Title = "Products";
}
#foreach (var p in Model.Products) {
<div class="item">
<h3>#p.Name</h3>
#p.Description
<h4>#p.Price.ToString("c")</h4>
</div>
}
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
</div>
HtmlHelper > PagingHelper.cs
namespace SportsStore.WebUI.HtmlHelpers {
public static class PagingHelpers {
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,
Func<int, string> pageUrl) {
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++) {
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
}
You could use AJAX. The first step is to put the contents that you want to be refreshed into a partial and into its own div:
#model SportsStore.WebUI.Models.ProductsListViewModel
#{
ViewBag.Title = "Products";
}
<div id="products">
#Html.Partial("_products", Model.Products)
</div>
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("Index", new { page = x }))
</div>
and then of course you will have the corresponding _Products.cshtml partial:
#model IEnumerable<SportsStore.WebUI.Models.ProductViewModel>
#foreach (var p in Model.Products) {
<div class="item">
<h3>#p.Name</h3>
#p.Description
<h4>#p.Price.ToString("c")</h4>
</div>
}
and then adapt your controller action so that it is capable of responding to AJAX requests:
public ActionResult Index(int page = 1)
{
var viewModel = new ProductsListViewModel
{
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
if (Request.IsAjaxRequest())
{
return PartialView("_Products", viewModel);
}
return View(viewModel);
}
and now all that's left is to AJAXify your pagination anchors. Could be done in a separate javascript file where you could use jQuery to subscribe to the .click() event of them and replace the default action with an AJAX request:
$(function() {
$('.pager a').click(function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(products) {
$('#products').html(products);
}
});
// prevent the default redirect
return false;
});
});

Creating a tree view

I wanted to create a tree view using MVC3 control toolkit and bind the data from the database dynamically to the recursive list.
Step 1: Get the details from the db to the obj like List or ArrayList
Step 2: Assign the List to viewdata in controller Action Result like
viewdata["name"]=List;
Step 3: Assign the viewdata to another List in cshtml treeview
ArrayList col = (ArrayList)ViewData["name"];
#if (col != null)
{
Html.Telerik().TreeView()
.Name("HierarchyTreeView")
.Items(items =>
{
for (int i = 0; i < col.Count; i++)
{
items.Add()
.Text(col[i].ToString())
.Value().Selected(True)
.Items((subItem) =>
{
subItem.Add()
.Text(Child.ToString()) //Here place child value
.Value();
});
}
}).ClientEvents(events => events
.OnSelect("onSelect")
).Render();
}
Step 4: Using the List assign the value to the tree view nodes using nested for loop
Step 5: Write onselect client event and get the selected value from Javascript and assign it to the javascript method of Grid filter.
function onSelect(e) {
var HNKey = treeView().getItemValue(e.item);
var HNText = treeView().getItemText(e.item);
}
Hope this will give some idea to start your process then from this you can ask questions.
I finally found better solution for this question..
I used jquery to create the tree which was much helpful for me.
After seaching for long time, I found something like this:
public class TreeView
{
public static List<Model> GetAllCategories()
{
string query="select * from tableName";
string connString = "connectionString";
var itemList = new List<Model>();
using (var con = new SqlConnection(connString))
{
using (var cmd = new SqlCommand(qry, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//added my code here to get the data..
itemList.Add(
new Model(){
categoryId= reader.GetInt32(reader.GetOrdinal("categoryId"))
)};
}
}
}
}
return itemList;
}
}
In the controller I wrote my code as:
public ActionResult Index()
{
List<Model> itemList= new List<Model>();
itemList = TreeView.GetAllCategories();
var president = itemList.
Where(x => x.Model.PAId == 0).ToList(); //
foreach (var item in president)
{
SetChildren(item, itemList);
}
return View(president);
}
private void SetChildren(Model model, List<Model> itemList)
{
var childs = itemList.
Where(x => (x.Model.PAId == model.categoryId)).ToList();
if (childs.Count > 0)
{
foreach (var child in childs)
{
SetChildren(child, itemListList);
model.Categories.Add(child);
}
}
}
Index.cshtml :
<div id="divtree">
#foreach (var item in Model)
{
<ul id="tree" >
<li>
#Html.ActionLink(item.Model.categoryName, "Action")
#Html.Partial("Childrens", item)
</li>
</ul>
}
</div>
<script type="text/javascript">
$(function () {
$('#treeViewContent').load('#Url.Action("CreateCategory","Category")');
$('#divtree').jstree({
"plugins": ["themes", "html_data", "ui", "cookies"]
})
.bind('loaded.jstree', function () {
$(this).jstree('open_all');
});
});
</script>
Childrens.cshtml:
#foreach (var item in Model.Categories)
{
<ul>
#if (item != null)
{
<li>
#Html.ActionLink(item.Model.categoryName, "Action")
#if (item.Categories.Count > 0)
{
#Html.Partial("Childrens", item)
}
</li>
}
</ul>
}
and finally got tree like this:

Resources