DropDownListFor get selected item value as parameter to controller - c#

Problem
I want my Html form to pass the value of the selected DropDownListFor to the controller but I can't figure out why the controller is not taking any value.
Im sending the value to the controller and trying to do some code with the selected value each time the user selects something but i can't manahe myselft to do it.
View
#Html.DropDownList("Fechas", "Todas")
<div id="target">
</div>
Javascript
$('#Fechas').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
var datafecha = $(this).val();
});
$("#Fechas").change(function () {
var dateSelected = $("select option:selected").first().text();
$.get('#Url.Action("Index")',
{ id: dateSelected }, function (data) {
$("#target").html(data);
});
});
Controller
public ActionResult Index(string id)
{
var db = Context();
string dateday;
string lines;
List<string> listItem2 = new List<string>();
List<string> listadesumas = new List<string>();
foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
{
dateday = Convert.ToString(item);
lines = dateday.Split(' ')[0];
listItem2.Add(lines);
}
var fechas = new SelectList(listItem2.ToList());
ViewBag.Fechas = fechas;
////////////-------------------/////////////
if (id == //SOMETHING)
{
// To do code comes here, which takes selectGroup as parameter
}
////////////_----------------------////////////
return View("~/Views/HomePos/Index.cshtml",db.Pos.ToList());
}
So how can i get my selected id as a parameter to use it in my controler and change data on the view? im not fully atached to javascript so if you have other approaches i will appreciate any help

Related

MVC - How to Return Multiple Attributes while using a dropdownlist

So basically you can refer to this in order to have a clearly view on what I want to achieve in my website.
The corresponding input such as Price and Item will get the information of the selected Gift Basket from database and appended inside the input tag so that the user can adjust the price or adding some item the the customer wanted.
Before Selecting a Gift Basket.
After Selecting a Gift Basket.
Is there any reference or example I can refer to in order to achieve this funtion
1- in the dropdown list add htmlAttributes onchange
#Html.DropDownListFor(model => model.GiftBasket, null, "--Select Gift Basket--", htmlAttributes: new { #class = "form-control ", onchange = "getprice()" }
2- insert below script to get price and item from controller
<script>
//get price & Item
function getprice() {
var strSelected1 = "";
$("#GiftBasket option:selected").each(function () {
strSelected1 += $(this)[0].value;
});
$.ajax({
url: "/your-Controller/getGiftBasket?GiftBasketID=" + strSelected1,
type: "post",
cache: false,
success: function (result) {
document.getElementById('price').value = result[0].price;
document.getElementById('item').value = result[0].item;
},
error: function () {
alert("something wrong");
}
});
};
</script>
3- insert below JsonResult to the controller
[HttpPost]
public JsonResult getGiftBasket(int? GiftBasketID)
{
var GiftBasketitem = db.Giftitem.Where(e => e.GiftBasketID== GiftBasketID).Select(e => new { e.item,e.price });
return Json(GiftBasket, JsonRequestBehavior.AllowGet);
}

How to get selected index changed value in controller mvc c#

I am getting value in a dropdown list and I wanted to get the selected value in controller when user select any value from the dropdown list. My view is -
#using (Html.BeginForm("ApReport", "Sales", FormMethod.Post))
{
#Html.DropDownList("Ddl", null, "All", new { #class = "control-label"})
#Html.Hidden("rddl")
}
controller -
[HttpPost]
public ActionResult ApReport(ApReport Ddl)
{
string Ddlvalue = string.Empty;
if (Request.Form["rddl"] != null)
{
Ddlvalue = Request.Form["rddl"].ToString();
}
}
but I am not getting any value. Also, I donot want to use any submit button.
Thanks in advance
The use of Ajax allows you as the developer to update the main view without reloading the entire page, as well as send data to the server in the background.
This is how I would have accomplished this task.
Firstly, I would have created an action in my controller which returns a JsonResult. This will return a JSON object to your calling jquery code, that you can use to get values back into your views. Here is an example of the action method.
[HttpGet]
public JsonResult YourActionName(string selectedValue) //Assuming key in your dropdown is string
{
var result = DoYourCalculation(selectedValue);
return Json(new { myResult = result }, JsonRequestBehavior.AllowGet);
}
Now, you need to add your jquery code. I would recommend you place this in a seperate javascript file referenced by your view.
Here is the JQuery code, with the ajax call to the Action in your controller. The Ajax call to the server is initiated by the 'change' event of your DropDown, handled in JQuery, as can be seen below.
$(function () {
$(document)
.on('change', '#Ddl', function(){
var valueofDropDown = $(this).val();
var url = '/YourControllerName/YourActionName';
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult ;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
};

Viewbag not updating

Currently on the I have some inline javascript, which makes an ajax call to a partial view controller which should have updated the viewbag along with it. However this does not seem to be the case, the data seems to persist from the main view which is null because it was never set there and if it was set then the data would still persist(tested).
Here is my javascript ajax call.
$.ajax({
url: btn.data('action-url'),
data: {
id: btn.data('id')
},
type: 'GET',
success: function (data) {
//delete all panels before showing new ones
$('.panel.panel-default').remove();
//push the new panels into the view
//$('#dash-content').html(data);
//Construct the partial view to be input into the main view
//Checks to see if browser supports templates
if ('content' in document.createElement('template')) {
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
for (var i = 0; i < widgetModel.length; i++) {
var clone = loadwidgets(widgetModel[i]); //This function is in an external js file
var inputDestination = document.querySelector('#col2');
inputDestination.appendChild(clone);
console.log(inputDestination);
}
}
and here is the Action that it is calling.
public ActionResult Dashboard(int? id)
{
ModelState.Clear();
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
ViewBag.widgets = getWidgetsQuery.ToList();
return PartialView();
}
Add an action to return the data i.e.
public ActionResult DashboardJson(int? id)
{
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
var widgets = getWidgetsQuery;
return Json(widgets, JsonRequestBehavior.AllowGet);
}
Declare and serialize your model above the json call as you have done:
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
Then within your success call simply re-assign it to the returned data:
widgetModel = data;

C# MVC4: Replace <div> when selection is made from a Html.DropDownList using jQuery

I need to be able to populate data into a <div> or some other sort of section from an object after the corresponding string has been selected from a drop down list (lazy loading).
When a chnage is made in the dropdownlist, I want the method in my controller to be called which will fill in <div id=result></div> with the output from the method.
Perhaps I am approaching this problem wrong.
I suspect the problem is in my JavaScript.
Here is my approach:
View:
<div>#Html.DropDownList("MyDDL") </div>
<br>
<div id="result"></div>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = "";
$("#MyDDL option:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "HomeController/showInfo";
//I suspect this is not completely correct:
$.post(url, {str: strSelected},function (result) {
$("result").html(result);
});
});
});
</script>
Controller (Perhaps I shouldn't be using PartialViewResult):
public ActionResult Index()
{
List<string> myList = new List<string>();
List<SelectListItem> MyDDL = new List<SelectListItem>();
myList.Add("Tim");
myList.Add("Joe");
myList.Add("Jim");
//fill MyDDL with items from myList
MyDDL = myList
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
ViewData["MyDDL"] = MyDDL;
return View();
}
[HttpPost]
public PartialViewResult showInfo(string str)
{
Person p = new Person(str); //name is passed to constructor
p.LoadInfo(); //database access in Person Model
ViewBag.Info = p.Info;
return PartialView("_result");
}
_result.cshtml:
<p>
#ViewBag.Info
</p>
Thanks You.
Change your script a little bit. Missing a # in the jQuery selecter for result div . Use the code given below
$.post(url, {str: strSelected},function (result) {
$("#result").html(result);
});
In my opinion if the javascript are in local don't need put $.post(url, {str: strSelected},function (result) {
You can use
//I suspect this is not completely correct:
$("#result").html(result);
try it
Did you try debugging p.LoadInfo() if it has any value? I also have some suggestions for your script:
Try adding keyup in your event so you can get the value in cases when the arrow keypad is used insted of clicking:
$("#MyDDL").on("change keyup", function () {
// you can get the dropdown value with this
var strSelected = $(this).val();
So I made the following changes and it worked:
View:
<div><%= Html.DropDownList("MyDDL") %> </div>
<br>
<span></span>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = $("#MyDDL option:selected").text();
var url = "/Home/showInfo";
$.post(url, {str: strSelected},function (result) {
$("span").html(result);
});
});
});
_result.cshtml:
#ViewBag.Info
The Controller was left unchanged.

There is no ViewData item with the key 'taskTypes' of type IEnumerable<SelectListItem>

I'm getting the error message above when adding an onchange attribute to a Html.DropDownList in ASP.NET MVC:
<td><%= Html.DropDownList("taskTypes", (IEnumerable<SelectListItem>)ViewData["TaskTypes"], "None", new { onchange = "document.getElementById('NewTask').submit()" })%></td>
When the view initially loads, I do not get the error. Only when posting back after the selected item is changed. My controller code is:
[AcceptVerbs(HttpVerbs.Get), RequiresAuthentication]
public ActionResult NewTask()
{
List<SelectListItem> dropDownData = new List<SelectListItem>();
List<SelectListItem> statusDropDownData = new List<SelectListItem>();
foreach (TaskStatus t in tasks.GetTaskStatus())
{
statusDropDownData.Add(new SelectListItem { Text = t.Status, Value = t.TaskStatusID.ToString() });
}
foreach (TaskType t in tasks.GetTaskTypes())
{
dropDownData.Add(new SelectListItem { Text = t.Reference, Value = t.TaskTypeID.ToString() });
}
ViewData["TaskStatus"] = statusDropDownData;
ViewData["TaskTypes"] = dropDownData;
if (Request["taskTypes"] != null)
{
string tt = Request["taskTypes"];
}
return View();
}
Does anyone know what the problem might be?
Thanks
The AcceptVerbs attribute on that controller method indicates that it will build up that ViewData instance and return the associated View to display your form. Are you certain that the controller method responsible for handling the form submission (or saving the data) is building up that ViewData instance in the same manner?

Categories

Resources