Update DropDownListFor data source from controller MVC - asp.net-mvc

I have a DropDownListFor that takes data source from controller. Is there a way to update it since i'm adding new values that i want then to be displayed on the same page.
View:
#Html.DropDownListFor(m => m.Id, MyController.GetIds(Model.Id).Select(g => new SelectListItem { Text = g.Text, Value = g.Value }), #Resource.System_Choose, new
{
#class = "form-control selectpicker",
data_live_search = "true"
})
Controller:
public static List<SelectListItem> GetIds(int Id)
{
var retVal = new List<SelectListItem>();
return retVal;
}

Make your View deal with Model that has property of type List<SelectListItem>() and return this property ready to be binded and displayed in DropDown.

There are some ways to achieve the goal,
Use only javascript to append the new value to select options. (If the new value doesn't send to backend)
Ajax and get the new list.
A sample for case 2, we can put the DropDownList to a partialview and use ajax to get the latest DropDownList in the partialview.
Controller :
public ActionResult QueryNewList()
{
return PartialView("~/Views/Home/_urPartialView.cshtml", viewModel);
}
Html:
<div id="myDiv"></div>
Js:
$.ajax({
dataType: "html",
url: "QueryNewList",
success: function (html) {
$("#myDiv").html("");
$("#myDiv").append(html);
}
})

Related

Confused about how to Populate DropDown thru ViewBag

I am a beginner to ASP.NET MVC technology. In my controller page I am using this code below
[HttpGet]
public ActionResult UrunEkle() {
List<SelectListItem> degerler = (from i in db.tblKategoriler.ToList()
select new SelectListItem
{
Text = i.KategoriAd,
Value = i.KategoriId.ToString()
}).ToList();
ViewBag.dgr = degerler;
return View(degerler);
}
this is view page
model MVCSTOK.Models.Entity.tblKategoriler
<div>
<label>Ürün Kategori</label>
#Html.DropDownListFor(m=>m.KategoriAd,(List<SelectListItem>)ViewBag.dgr, new { #class = "form-control" });
</div>
I am geting this error
The model item passed into the dictionary is of type System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]', but this dictionary requires a model item of type 'MVCSTOK.Models.Entity.tblKategoriler.
Your returning data's type isn't corresponding to MVCSTOK.Models.Entity.tblKategoriler, that you return it from UrunEkle() Action method. You return List<SelectListItem>, but your View's type of model is MVCSTOK.Models.Entity.tblKategoriler.
I think you can do (return view without model):
[HttpGet]
public ActionResult UrunEkle() {
List<SelectListItem> degerler = (from i in db.tblKategoriler.ToList()
select new SelectListItem
{
Text = i.KategoriAd,
Value = i.KategoriId.ToString()
}).ToList();
ViewBag.dgr = degerler;
return View();
}
And you can do this in .cshtml view (without model):
<div>
<label>Ürün Kategori</label>
#Html.DropDownListFor(m=>m.KategoriAd,(List<SelectListItem>)ViewBag.dgr, new { #class = "form-control" });
</div>

Updating a Partial View From A Link In Its Own WebGrid

This is pretty much my third day developing MVC and I have what I hope will be a simple question. Basically I have a WebGrid within a partial view, which has a column that performs an update via a controller.
The controller then returns the updated partial view successfully, but the it replaces the whole page with the results instead of just the partial view.
Here's the partial view:
#model Site.Models.UsersForCompanyModel
#{
ViewBag.Title = "Admin User Management Grid";
}
#{
var grid = new WebGrid(
Model.Users,
ajaxUpdateContainerId: "divUserGrid",
fieldNamePrefix: "gridItems_",
pageFieldName: "paging",
sortFieldName: "sortField"
);
grid.Pager(WebGridPagerModes.All);
var userColumns = new List<WebGridColumn>
{
new WebGridColumn {ColumnName = "Email", Header = "E-Mail", CanSort = true},
new WebGridColumn {Header = "Lock", Format = user => user.isAdmin ? Html.Raw("n/a") : Html.ActionLink(user.IsLocked ? "Unlock" : "Lock", "ToggleLock", new {userId = user.Id, companyId = Model.CompanyId}) },
};
<div id="divUserGrid">
#grid.GetHtml(
htmlAttributes: new { id = "userGrid" },
tableStyle: "table table-striped table-bordered",
columns: userColumns
)
</div>
}
...and here's the controller code:
public ActionResult GetUsersForCompany(string companyId)
{
using (var service = new ManagementService())
{
var model = GetUsersForCompany(companyId, service);
return PartialView("AdminUserManagement_Grid", model);
}
}
public ActionResult ToggleLock(string companyId, string userId)
{
using (var service = new ManagementService())
{
var user = service.GetUserById(userId);
service.LockUser(userId, !user.IsLocked);
return GetUsersForCompany(companyId);
}
}
What's the easiest way to go about updating the partial view with the results returned from ToggleLock()?
Is there a way to do it declaratively via Html.ActionLink or Ajax.ActionLink?
The easiest way is to put your partial view in container div like below
<div id="PartialViewDivId">
#{ Html.RenderAction("GetUsersForCompany",model.CompanyId);}
</div>
Then use jQuery to load the updated view
On some click event
var companyId= read company id
var userId= read user id
var url = "mycontroller/ToggleLock?companyId="+companyId+"&userId"+userId;
$("#PartialViewDivId").load(url)
Thanks, Kartikeya. Partial credit for the answer, though I found a declarative way that didn't require manual HTML/event wiring and custom javascript.
The key was simply switching to an Ajax.ActionLink (instead of using Html.ActionLink), then setting my partial view placeholder ID (I had a div setup similar to Kartikeya's example) and a few other parameters in the AjaxOptions of the control, like this:
new WebGridColumn {Header = "Lock",
Format = user => user.isAdmin ? Html.Raw("n/a") :
Ajax.ActionLink( user.IsLocked ? "Unlock" : "Lock",
"ToggleLock",
new{userId = user.Id, companyId = Model.CompanyId },
new AjaxOptions
{
UpdateTargetId="userGridPlaceholder", // <-- my grid placeholder
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})

How to Load a standard MVC dropdownlist

I am merely trying to get items into an Html.DropDownList() as follows. I've debugged and know the data is coming across to the View but the dropdownlist is not displayed. Anyone know where I'm going wrong here?
#model List<ControlNumberViewer.Models.Table>
#{
Layout = null;
}
Control Number Viewer
<div id="PickTable">
#{Html.DropDownList("TableName", Model.Select(x => new SelectListItem
{
Text = x.TableName,
Value = x.TableName
}));
}
</div>
Pull your data into the controller and store it in a ViewBag. Then use DropDownListFor for strongly typed access to the data for the property TableName.
in your controller:
var linqQuery = _db.SQLTable.Select(x => new { Text = x.TableName, Value = x.TableName });
ViewBag.ListValues = new SelectList(linqQuery, "Value", "Text");
in your view:
#Html.DropDownListFor(m => m.TableName, ViewBag.ListValues as SelectList);
#{
var listitem = Model.Select(x => new SelectListItem {
Text = x.TableName,
Value = x.TableName
});
Html.DropDownList("TableName", (SelectList)listitem);
}

How to assign value to dropdown for viewbag element?

I am developing MCV app with Razor syntax.
I have pass the elements to the dropdown list and I want to show selected item in that dropdown from viewbag element.
below code displays the dropdow code.
Controller Code
[SessionFilterAction]
public ViewResult Details(int id)
{
ViewBag.HODList = new SelectList(db.Employees.Where(e => e.DesignationType == "HOD"), "Id", "FullName");
ViewBag.ItemToBeSelectedInList = 5;
return View(paymentadvice);
}
View Code
if(ViewBag.DesignationTypeOfLoggedUser == "Staff")
{
#Html.DropDownList("HODList", String.Empty ,new { ???? })
}
Now I want to use viewbag element which will be select the one of the item of dropdown.
How to do this ?
ViewBag is designed to pass data from the controller to the view not to the other way.
You can use HTTP Get method for populating drop down like
[HttpGet]
public MyAction()
{
MyModel model = new MyModel();
// model.DropDwonValues is generic list class in model
model.DropDwonValues= db.Values //replace with your db table
.Select(v => new DropDownItem
{
Text = v.Name //value to go in your text field
Value = v.Id.ToString() //value to go in your ID field
})
.ToList();
return View(model);
}
Then in your view you can do:
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.DropDownId)
#Html.DropDownListFor(m => m.DropDownId , Model.DropDwonValues )
}

ASP.NET MVC Html.DropDownList populated by Ajax call to controller?

I wanted to create an editor template for a field type that is represented as a dropdownlist. In the definition of the editor template I would like to populate the DropDownList using a call to an action on the controller returning the results as JSON - Any ideas how to do this?
E.g something like:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TheFieldType>" %>
<%= Html.DropDownList(.....
In the editor template provide an empty dropdown:
<%= Html.DropDownListFor(
x => x.PropertyToHoldSelectedValue,
Enumerable.Empty<SelectListItem>(),
"-- Loading Values --",
new { id = "foo" })
%>
Then setup a controller action that will return the values:
public class FooController: Controller
{
public ActionResult Index()
{
return Json(new[] {
new { Id = 1, Value = "value 1" },
new { Id = 2, Value = "value 2" },
new { Id = 3, Value = "value 3" },
}, JsonRequestBehavior.AllowGet);
}
}
And then populate the values using AJAX:
$(function() {
$.getJSON('/foo/index', function(result) {
var ddl = $('#foo');
ddl.empty();
$(result).each(function() {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
});
});
I know this post is a few years old but I found it and so might you. I use the following solution and it works very well. Strong typed without the need to write a single line of Javascript.
mvc4ajaxdropdownlist.codeplex.com
You can download it via Visual Studio as a NuGet package.

Resources