binding dropdownlist in mvc3 Razor(default Dropdownlist value is not selected) - asp.net-mvc-3

I am binding dropdownlist in mvc3 Razor.
My problem is its not showing default Dropdownlist value selected.An Empty space is shown.
Code is given below:
#Html.DropDownListFor(model => model.MainHeadingFont, new SelectList(Model.lst_FontType, "Value", "Text"), new { #class = "inputPage7Select" })
CollectionList is passed from Model:
public List<SelectListItem> lst_FontType
{
get
{
FontType.RemoveRange(0, FontType.Count);
FontType.Add(new SelectListItem() { Text = "\"Gill Sans MT\", Arial, sans-serif", Value = "\"Gill Sans MT\", Arial, sans-serif", Selected = true });
FontType.Add(new SelectListItem() { Text = "\"Palatino Linotype\", Times, serif", Value = "\"Palatino Linotype\", Times, serif" });
FontType.Add(new SelectListItem() { Text = "\"Times New Roman\", Times, serif", Value = "\"Times New Roman\", Times, serif" });
return FontType;
}
}

In the controller action rendering this view:
public ActionResult Index()
{
var model = ...
model.MainHeadingFont = "\"Palatino Linotype\", Times, serif";
return View(model);
}
This will automatically preselect the second element of the ddl.

Related

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 display a List of objects in C# to javascript using Google JS API in MVC3?

I have a .Net MVC3 website where I want to draw Pie Charts, but the Google Charts API or maybe JSON doesn't work right in my code and I don't know why.
I tried to refer from this sets of codes: MVC4 with Google JS API
This is my ChartController Code:
public ActionResult Sales()
{
return Json(CreateList(), JsonRequestBehavior.AllowGet);
}
public class ItemForChart
{
public String Name { get; set; }
public Int32 Qty { get; set; }
}
public IEnumerable<ItemForChart> CreateList()
{
List<ItemForChart> list = new List<ItemForChart>();
ItemForChart itm1 = new ItemForChart() { Name = "A", Qty = 1 };
ItemForChart itm2 = new ItemForChart() { Name = "B", Qty = 2 };
ItemForChart itm3 = new ItemForChart() { Name = "C", Qty = 3 };
ItemForChart itm4 = new ItemForChart() { Name = "D", Qty = 4 };
list.Add(itm1); list.Add(itm2); list.Add(itm3); list.Add(itm4);
return list;
}
This is my View Code for the Sale ActionResult
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" >
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/Chart/Sales', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Name');
tdata.addColumn('number', 'Qty');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Qty);
}
var options = {
title: "Sample Charts"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
var chart3 = new google.visualization.PieChart(document.getElementById('chart_div3'));
var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));
chart1.draw(tdata, options);
chart2.draw(tdata, options);
chart3.draw(tdata, options);
chart4.draw(tdata, options);
});
}
</script>
<div id="chart_div1" style="width: 900px; height: 500px;">
</div>
<div id="chart_div2" style="width: 900px; height: 500px;">
</div>
<div id="chart_div3" style="width: 900px; height: 500px;">
</div>
<div id="chart_div4" style="width: 900px; height: 500px;">
</div>
And when I run the program, it shows this,
[{"Name":"A","Qty":1},{"Name":"B","Qty":2},{"Name":"C","Qty":3},{"Name":"D","Qty":4}]
^it doesn't show any charts but only that.
or if there are other Charts API that I can use that is also easy to learn, I am open for suggestion.
It seems like you are browsing to the JSON controller endpoint localhost/MyApp/Chart/Sales (which is consumed by the Ajax callback in google.setOnLoadCallback to feed data to the chart) - it looks like the JsonRresult is working fine. In order to view the Graph, you'll need to browse to the "Sale ActionResult" route (something like localhost/MyApp/SomeController/Sale)
You also have a typo:
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Qty]);
// ^ closing array brace
}
Fixed jsFiddle
Not directly related, but note that you can use Object initializer syntax on the server C# to simplify matters:
public IEnumerable<ItemForChart> CreateList()
{
return new List<ItemForChart>
{
new ItemForChart() { Name = "A", Qty = 1 },
new ItemForChart() { Name = "B", Qty = 2 },
new ItemForChart() { Name = "C", Qty = 3 },
new ItemForChart() { Name = "D", Qty = 4 }
}
}

How can I access the values of my view's dropdown list in my controller?

How can I access the values of my view's dropdown list in my controller?
var typeList = from e in db.Rubrics where e.DepartmentID == 2 select e;
var selectedRubrics = typeList.Select(r => r.Category);
IList <String> rubricsList = selectedRubrics.ToList();
IList<SelectListItem> iliSLI = new List<SelectListItem>();
SelectListItem selectedrubrics = new SelectListItem();
selectedrubrics.Text = "Choose a category";
selectedrubrics.Value = "1";
selectedrubrics.Selected = true;
iliSLI.Add(selectedrubrics);
for(int i = 0;i<rubricsList.Count();++i)
{
iliSLI.Add(new SelectListItem() {
Text = rubricsList[i], Value = i.ToString(), Selected = false });
}
ViewData["categories"] = iliSLI;
In my view this works fine showing the dropdown values:
#Html.DropDownList("categories")
Then in my controller I am using FormCollection like this:
String[] AllGradeCategories = frmcol["categories"].Split(',');
When I put a breakpoint here, I get an array of 1’s in AllGradeCategories. What am I doing wrong?
MORE:
Here’s my begin form:
#using (Html.BeginForm("History", "Attendance",
new {courseID = HttpContext.Current.Session ["sCourseID"] },
FormMethod.Post, new { #id = "formName", #name = "formName" }))
{
<td>
#Html.TextBoxFor(modelItem => item.HomeworkGrade, new { Value = "7" })
#Html.ValidationMessageFor(modelItem => item.HomeworkGrade)
</td>
<td>
#Html.TextBoxFor(modelItem => item.attendanceCode, new { Value = "1" })
#Html.ValidationMessageFor(model => model.Enrollments.FirstOrDefault().attendanceCode)
</td>
<td>
#Html.EditorFor(modelItem => item.classDays)
</td>
<td>
#Html.DropDownList("categories")
</td>
}
My controller signature:
public ActionResult ClassAttendance(InstructorIndexData viewModel, int id, FormCollection frmcol, int rows, String sTeacher, DateTime? date = null)
EDITED 2
Tried this but although it seems to get posted, the I still don’t get the values of the list in the hidden field or the categories parameter.
#Html.Hidden("dropdownselected1");
#Html.DropDownList("categories",ViewBag.categories as SelectList, new { onchange = "changed" })
</td>
$(function () {
$("#dropdownselected1").val($("#categories").val());
});
If you are looking to access the selected value from the dropdown list, use a hidden field and repopulate that field on onChange() javascript event of the dropdown list.
but you can use normal
#Html.Hidden("dropdownselected1");
#Html.DropDownList("categories",new { onchange ="changed();"}
function changed()
{
$("#hiddenfieldid").val($("#dropdownlistid").val());
}
should do.
I ended up creating a ViewModel to handle just the drowdown list with an associated partial view. Then in the controller I accessed the values of the list using FormCollection().

Paging/Sorting not working on web grid used in Partial View

I have a partial view where I am showing a web grid depending upon a value selected from a page.
For drop down I have used
#Html.DropDownListFor(
x => x.ItemId,
new SelectList(Model.Items, "Value", "Text"),
new {
id = "myddl",
data_url = Url.Action("Foo", "SomeController")
}
)
For drop down item select I have used
$(function() {
$('#myddl').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#result').load(url, { value: value })
});
});
and below is my action
public ActionResult Foo(string value)
{
SomeModel model = ...
return PartialView(model);
}
everything works good, but when I try doing a paging or sorting on my webgrid which is on my partial view I am showing a new window with the web grid.
I wanted to be able to sort and page on the same page without postback
Please help
The following example works fine for me.
Model:
public class MyViewModel
{
public string Bar { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Foo(string value)
{
var model = Enumerable.Range(1, 45).Select(x => new MyViewModel
{
Bar = "bar " + value + " " + x
});
return PartialView(model);
}
}
Index.cshtml view:
<script type="text/javascript">
$(function () {
$('#myddl').change(function () {
var url = $(this).data('url');
var value = $(this).val();
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: value },
success: function (result) {
$('#result').html(result);
}
});
});
});
</script>
#Html.DropDownList(
"id",
new[] {
new SelectListItem { Value = "val1", Text = "value 1" },
new SelectListItem { Value = "val2", Text = "value 2" },
new SelectListItem { Value = "val3", Text = "value 3" },
},
new {
id = "myddl",
data_url = Url.Action("Foo", "Home")
}
)
<div id="result">
#Html.Action("Foo")
</div>
Foo.cshtml partial:
#model IEnumerable<MyViewModel>
#{
var grid = new WebGrid(
canPage: true,
rowsPerPage: 10,
canSort: true,
ajaxUpdateContainerId: "grid"
);
grid.Bind(Model, rowCount: Model.Count());
grid.Pager(WebGridPagerModes.All);
}
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column("Bar")
)
)
Notice that I have used a GET request to refresh the grid instead of POST because this way the value query string parameter selected in the dropdown is preserved for future sorting and paging.

How do I process drop down list change event asynchronously?

I have a drop down list that I need to react to asynchronously. I cannot get the Ajax.BeginForm to actually do an asynchronous postback, it only does a full postback.
using (Ajax.BeginForm("EditStatus", new AjaxOptions { UpdateTargetId = "divSuccess"}))
{%>
<%=Html.DropDownList(
"ddlStatus",
Model.PartStatusList.OrderBy(wc => wc.SortOrder).Select(
wc => new SelectListItem
{
Text = wc.StatusDescription,
Value = wc.PartStatusId.ToString(),
Selected = wc.PartStatusId == Model.PartStatusId
}),
new { #class = "input-box", onchange = "this.form.submit();" }
)%>
<div id='divSuccess'></div>
<%
}
When the user selects an item from the list, it does a full postback and the controller method's return value is the only output on the screen. I am expecting the controller method's return value to be displayed in "divSuccess".
[AjaxAwareAuthorize(Roles = "Supplier_Administrator, Supplier_User")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditStatus(PartPropertiesViewModel partPropertiesViewModel)
{
var part = _repository.GetPart(partPropertiesViewModel.PartId);
part.PartStatusId = Convert.ToInt32(Request.Form["ddlStatus"]);
_repository.SavePart(part);
return Content("Successfully Updated Status.");
}
How about doing this the proper way using jQuery unobtrusively and getting rid of those Ajax.* helpers?
The first step is to use real view models and avoid the tag soup in your views. Views should not order data or whatever. It's not their responsibility. Views are there to display data that is being sent to them under the form of a view model from the controller. When I see this OrderBy in your view it's just making me sick. So define a clean view model and do the ordering in your controller so that in your view you simply have:
<% using (Html.BeginForm("EditStatus", "SomeControllerName", FormMethod.Post, new { id = "myForm" }) { %>
<%= Html.DropDownListFor(
x => x.Status,
Model.OrderedStatuses,
new {
#class = "input-box",
id = "myDDL"
}
) %>
<% } %>
<div id="divSuccess"></div>
and finally in a completely separate javascript file subscribe for the change event od this DDL and update the div:
$(function() {
$('#myDDL').change(function() {
var url = $('#myForm').attr('action');
var status = $(this).val();
$.post(url, { ddlStatus: status }, function(result) {
$('#divSuccess').html(result);
});
});
});
This assumes that in your controller action you would read the current status like this:
[AjaxAwareAuthorize(Roles = "Supplier_Administrator, Supplier_User")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditStatus(PartPropertiesViewModel partPropertiesViewModel, string ddlStatus)
{
var part = _repository.GetPart(partPropertiesViewModel.PartId);
part.PartStatusId = Convert.ToInt32(ddlStatus);
_repository.SavePart(part);
return Content("Successfully Updated Status.");
}
And when you see this you might ask yourself whether you really need a form in this case and what's its purpose where you could simply have a dropdownlist:
<%= Html.DropDownListFor(
x => x.Status,
Model.OrderedStatuses,
new Dictionary<string, object> {
{ "class", "input-box" },
{ "data-url", Url.Action("EditStatus", "SomeControllerName") },
{ "id", "myDDL" }
}
) %>
<div id="divSuccess"></div>
and then simply:
$(function() {
$('#myDDL').change(function() {
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ddlStatus: status }, function(result) {
$('#divSuccess').html(result);
});
});
});

Resources