get dropdownlist selected value in controller MVC3 Razor - asp.net-mvc

Hi in my MVC3 Project with RAZOR, i Have one doubt.
i have a page named CatlogPage.cshtml. in that page i have a Dropdownlist control.
#(Html.Telerik().DropDownListFor(m => m.CatalogName)
.BindTo(Model.CatalogName).HtmlAttributes(new { style = "width:235px" }))
<input type="submit" value="Next" />
I have a controller named Hierarchy.cs:
in that controller,
public ActionResult Hierarchy()
{
// Need to get the selected value in DropDownList
return View("Hierarchy");
}
How to get the value(CatalogName) from dropDownList to the controller?
This is my model code.
public List<SelectListItem> GetCatalogNameModel()
{
try{
var cat = from s in _entities.Catalogs.ToList()
select new SelectListItem()
{
Text = s.CatalogName,
Value = s.CatalogName
};
return cat.ToList();}
catch (Exception ex)
{
CreateLogFiles.ErrorLog(HttpContext.Current.Server.MapPath("~/Logs/ErrorLog"), ex, "CatalogService", "GetCatlogName");
return null;
}
}

So assuming that the first code snippet is from a strongly typed view (object DatabaseModel.CatalogModel) and that you are submitting the form to the Hierachy method, then passing in a CatalogModel and accessing the CatalogName should be what your after?
i.e.
public ActionResult Hierarchy(DatabaseModel.CatalogModel inputModel)
{
inputModel.CatalogName; //This will be the value from the drop down list
return View("Hierarchy");
}

For DropDownList, I use an Int prop to receive the selected Id. So My answer is:
Add this property to your ViewModel:
public Int32 SelectedCatalogId {get;set;}
And bind it to the DropDownList:
#Html.DropDownListFor(m => m.SelectedCatalogId, Model.GetCatalogNameModel())

Related

How to configure an MVC dropdown depending on which view calls it

I have two views, BatchReceipt and Receipt which utilise the same model. Until now they have used the same display template of ReceiptType. But I want to have one exclude certain items and the other to have the full list (so essentially a second .cshtml display template called ReceiptTypeFull). How do I configure each of these views in Visual Studio to utilise the different Display Templates?
Some additions to show the code being used:
I have file ReceiptType.cshtml being used as a DisplayTemplate which contains the following to setup the receipt dropdown
#using Clinton.Web.Helpers.EnumHelpers
#{
var item = EnumsHelper.GetNameFromEnumValue(Model);
}
I want to use a different DisplayTemplate, call it ReceiptTypeFull.cshtml
#using Clinton.Web.Helpers.EnumHelpersFull
#{
var item = EnumsHelper.GetNameFromEnumValue(Model);
}
#item
The difference is in calling the enumhelper or the enumhelperfull to vary the query populating the dropdown. My problem is that I cannot see how to redirect the view to use the different enumhelper/displaytemplate/
Thanks
I think I understand what you are getting at. You want to control which template is used for an Enum in the view.
I will explain using editor templates but it works the same way if you use display templates. You should be able to follow and apply for your scenario.
The idea is to use this overload of the editor html helper.
public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName);
It is called like this
#Html.Editor("{property name}", "{template name}").
Below is an example to show it being used.
Suppose we have this enum
public enum MyItems
{
Item1 = 1,
Item2 = 2,
Item3 = 3
}
This helper
public static class MyEnumHelper
{
public static List<MyItems> GetAllItems()
{
return new List<MyItems>()
{
MyItems.Item1,
MyItems.Item2,
MyItems.Item3
};
}
public static List<MyItems> GetSomeItems()
{
return new List<MyItems>()
{
MyItems.Item1,
MyItems.Item2
};
}
}
This controller
public class HomeController : Controller
{
public ActionResult AllItems()
{
return View();
}
public ActionResult SomeItems()
{
return View();
}
}
We have these 2 editor templates, which are put in views/shared/editortemplates
First one called MyItems.cshtml which is the all one
#model MyItems?
#{
var values = MyEnumHelper.GetAllItems().Cast<object>()
.Select(v => new SelectListItem
{
Selected = v.Equals(Model),
Text = v.ToString(),
Value = v.ToString()
});
}
#Html.DropDownList("", values)
Second one called MyItems2.cshtml which is the some one
#model MyItems?
#{
var values = MyEnumHelper.GetSomeItems().Cast<object>()
.Select(v => new SelectListItem
{
Selected = v.Equals(Model),
Text = v.ToString(),
Value = v.ToString()
});
}
#Html.DropDownList("", values)
Then in the AllItems.cshtml to get the MyItems.cshtml template called we need
#model MyItemsViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.MyItem)
<submit typeof="submit" value="submit"/>
}
And in the SomeItems.cshtml to get some of the items by calling MyItems2.cshtml we use
#model MyItemsViewModel
#using (Html.BeginForm())
{
#Html.Editor("MyItem", "MyItems2") #* this bit answers your question *#
<submit typeof="submit" value="submit" />
}

asp.net mvc displaying dropdown value

I have created a dropdownlist by fetching data from database.I want to display the selected value on click of submit. In controller I am trying to store the selected value in ViewBag and display it. When I debugged the code, I came to know that viewbag stores null value.The following line stores the value in viewbag.
ViewBag.scode = emp.Service_Code;
While debugging, Service_Code shows the value but it gets stored as null in ViewBag. Please help me in solving this issue.
Model
public class Employee
{
public int Service_Code { get; set; }
public string Service_Name { get; set; }
public IEnumerable<SelectListItem> ser_code { get; set; }
}
View
#model mvclearn.Models.Employee
#{
ViewBag.Title = "menu";
}
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<div class="container">
#using (Html.BeginForm("save", "Test", FormMethod.Post))
{
#Html.DropDownListFor(m => m.Service_Code, Model.ser_code, "--select-",new { #class = "form-control" })
<input type="submit" value="submit" class="btn-block" />
}
</div>
<div>You entered:#ViewBag.scode</div>
Controller
public ActionResult menu()
{
RevenueDashboardEntities rdb = new RevenueDashboardEntities();
var model = new Employee()
{
ser_code = new SelectList(db.Services, "Service_Code", "Service_Name")
};
return View(model);
}
[HttpPost]
public ActionResult save(Employee emp)
{
RevenueDashboardEntities rdb = new RevenueDashboardEntities();
ViewBag.scode = emp.Service_Code;
return View("menu");
}
The selected value is already getting post in the action via model in Service_Code property of it.
What you need here is return your model back to view and it will populate the selected value with what was selected at form post:
[HttpPost]
public ActionResult save(Employee emp)
{
RevenueDashboardEntities rdb = new RevenueDashboardEntities();
// this is needed to populate the items of dropdown list again
emp.ser_code = new SelectList(db.Services, "Service_Code", "Service_Name");
// sending model back to view
return View("menu",emp);
}
Now the value will be auto selected on page load after form is posted and you can display the value on the page inside div by writing:
<div>You entered: #Model.Service_Code</div>

How to retrive Value of selected GroupDropdown on controller side

As I am new in MVC I dont know. How could I get the value of selected GroupDropdown on controller side. Here I am Binding by dropdown using json
#using (Html.BeginForm("Index", "Property"))
{
#Html.AntiForgeryToken()
<select id="GroupDropdown" onchange="CallSubGroup(this.value);" class="form-control"></select>
}
My controller side code is below still not getting the value.
[HttpPost]
public ActionResult Index(tblProperty property, FormCollection data)
{
foreach (var key in data.AllKeys)
{
var value = data[key];
// etc.
}
}
Just add the name attribute to select.
<select name="GroupDropdown" id="GroupDropdown" onchange="CallSubGroup(this.value);" class="form-control"></select>
MVC wants name values on the form elements to use as the key.
Html
#using (Html.BeginForm("Index", "Property"))
{
#Html.AntiForgeryToken()
<select name="GroupDropdown" id="GroupDropdown" onchange="CallSubGroup(this.value);" class="form-control"></select>
}
Controller
[HttpPost]
public ActionResult Index(tblProperty property, FormCollection data)
{
string value = data["GroupDropdown"]
//do things
Return View();
}

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 )
}

Set HTML dropdownlist selected item using value from ViewModel

I have an HTML dropdown list:
<select name="status">
<option value="close" >Close Task</option>
<option value="open" >Reopen Task</option>
</select>
I want to set the 'selected' option based on the 'Task.Completion' property in my view model:
public class TaskEditViewModel
{
public Task Task { get; set; }
public TaskComment TaskComment { get; set; }
}
So if Task.Completion is NULL, the 'close' option is selected, otherwise the 'open' option is selected.
How can I do this?
Your view model doesn't seem adapted to what you are trying to do in the view (which according to your question is show a dropdown list and preselect a value based on some property on your view model).
So a far more realistic view model would be this:
public class TaskEditViewModel
{
public string Completion { get; set; }
public IEnumerable<SelectListItem> Actions
{
get
{
return new[]
{
new SelectListItem { Value = "close", Text = "Close Task" },
new SelectListItem { Value = "open", Text = "Reopen Task" },
};
}
}
}
then you could have a controller action which will populate and pass this view model to the view:
public ActionResult Foo()
{
var model = new TaskEditViewModel();
// this will automatically preselect the second item in the list
model.Completion = "open";
return View(model);
}
and finally inside your strongly typed view you could use the DropDownListFor helper to render this dropdown:
#model TaskEditViewModel
#Html.DropDownListFor(x => x.Completion, Model.Actions)

Resources