asp.net mvc displaying dropdown value - asp.net-mvc

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>

Related

Viewbag not properly working transfer the wrong data

I am student. I am new to ASP.NET MVC and I google it and I tried see I write all code but viewbag not properly working
I am transferring data and using the viewing but not transferring the dropdown value
type.cs
public class Type
{
//public int Value { get; set; }
//public string Text { get; set; }
public int typeid { get; set; }
public string typename { get; set; }
}
public class TypeViewModel
{
//public List<Type> TypeDetaills { get; set; }
public SelectList TypeList { get; set; }
}
HomeControlle.cs
TypeViewModel TypeViewModel = new TypeViewModel();
public ActionResult Index()
{
SqlCommand cmd = new SqlCommand("getType", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
DataTable dt = ds.Tables[0];
List<Type> objcountry = new List<Type>();
SelectList objlistofcountrytobind = new SelectList(dt.AsDataView(), "typeid", "typename", 0);
TypeViewModel.TypeList = objlistofcountrytobind;
ViewBag.typename = TypeViewModel.TypeList;
cn.Close();
return View();
}
[HttpPost]
public ActionResult CreateCustomer(Customer customer,string TypeList)
{
customer.Type = TypeList;
customer.CustomerName = cust;
return RedirectToAction("Index");
}
Index.cshtml
#model projectname.Models.TypeViewModel
#{
ViewBag.Title = "Index";
//var t = ViewBag.typename;
}
<h2>Type Query</h2>
#using (Html.BeginForm("CreateCustomer", "Home", FormMethod.Post, new { TypeList = #ViewBag.typename }))
{
<div class="form-group">
<div class="row">
<label>Type Name:</label>
#Html.DropDownListFor(model => model.TypeList, ViewBag.typename as SelectList)
#*#Html.Hidden("TypeList", #ViewBag.typename);*#
#*#Html.HiddenFor("TypeList", #ViewBag.typename);*#
#*#Html.HiddenFor(x => x.TypeList)*#
#*<input type="hidden" value="#ViewBag.typename" />*#
#*#Html.DropDownList("typeid", t as SelectList)*#
#*#Html.DropDownListFor(x => x.typename, new SelectList((IEnumerable<Type>)t, "typeid", "typename"))*#
</div>
</div>
<div class="form-group">
<div class="row">
<label>Customer Name:</label>
<input type="text" id="cust" name="cust" />
</div>
</div>
<input type="submit" />
}
see i select the runtime warranty from the drop down
I am trying to pass controller warranty not 2
see stored procedure getType fill this stored procedure in dropdown
I tried hiddenfor attribute but it not work
I want the pass warranty to createcustomer controller not 2
please help
Before trying to create code, you have to learn that the first letter in MVC is for model. So you have forget that viewbag is even exist. Create a view model , assign data and pass it from the action and use it inside of the view
TypeViewModel.TypeList = objlistofcountrytobind;
return View (TypeViewModel)
and you can only assign as a hidden (or not hidden) the primitive types (as string or int) not the whole instanse of the class
Pass text and value field same, if you want the text field to be posted back to the controller action method. By default dropdownlist uses value field.
Change that line!
SelectList objlistofcountrytobind = new SelectList(dt.AsDataView(), "typename", "typename", 0);
You can modify your view model as described in the following post: How to get DropDownList SelectedValue in Controller in MVC.
Or you can use the JavaScript:
#Html.DropDownListFor(model => model.TypeList,
ViewBag.type_name as SelectList,
new { onchange=" { var ddltext = $(`#TypeList option:selected`).text();$('#textvalue').val(ddltext);}" })
#Html.Hidden("typeList", "")
<script src="~/Scripts/jquery-3.3.1.min.js"></script>

How to pass a selected object to a Controller using Html.DropDownListFor

I'm currently trying to pass a object called DropDown from a View to a controller action using HTML.DropDownFor() and a form.
The object looks like this:
public class DropDown
{
public int id { get; set; }
public string value { get; set; }
}
The view Model looks like this:
public class GraphViewModel
{
public DropDown SelectedGraphTypeDropDown { get; set; }
public IEnumerable<DropDown> GraphTypeDropDowns { get; set; }
}
The controller action looks like this:
[HttpPost]
public string GetTestData(DropDown SelectedGraphTypeDropDown)
{
// use above object here
}
And the view like so:
#using (Html.BeginForm("GetTestData", "Graph", FormMethod.Post))
{
#Html.DropDownListFor(m => m.SelectedGraphTypeDropDown, new SelectList(Model.GraphTypeDropDowns, "id", "value"))
<input type="submit" />
}
Rendered HTML
What I expect to happen is the selected GraphType will be passed to the GetTestData action and resolved as a whole object called "SelectedGraphTypeDropDown".
I have debugged through it and it seems that the selected GraphType id (int) is passed to the controller but the whole object is not. I have also tried to pass each field of the selectedGraphTypeDropDown but this wont work as the fields are set after the page is rendered.
Also is there a way to pass the full viewModel to the controller?
Any advice would be apricated thanks!
Firstly,dropdown cannot pass a model,but you can add hidden input to bind value.Here is a demo:
view:
#using (Html.BeginForm("GetTestData", "Graph", FormMethod.Post))
{
#Html.DropDownListFor(m => m.SelectedGraphTypeDropDown.id, new SelectList(Model.GraphTypeDropDowns, "id", "value"))
<input id="value" name="SelectedGraphTypeDropDown.value" hidden/>
<input type="submit" />
}
js(js will bind selected value to hidden input):
$(function () {
$("#value").val($(this).find("option:selected").text());
})
$("#SelectedGraphTypeDropDown_id").change(function () {
$("#value").val($(this).find("option:selected").text());
})
result:

Retrieving values from partial view during post method

I have a view which contains a dropdown list and on dropdownlist item being selected I load a partial view. And when the form is submitted I want to be able to get both the values from main view and partial view during form submit.
Here is the main view
#model AdminPortal.Areas.Hardware.Models.CreateModule
#{
ViewBag.Title = "Create Module";
Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}
#Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<legend>Add a Module <small>Create</small></legend>
#using (Html.BeginForm("CreateModule", "Module", new{id="AddModuleForm"}))
{
#Html.ValidationSummary(true)
<div class ="controls">
<div class="input-block-level">#Html.TextBoxFor(model => model.ModuleId, new {#placeholder = "ModuleID"})</div>
<br/>
<div class ="input-block-level" id="selectedModuleTypeName">#Html.DropDownListFor(model => model.SelectedModuleTypeName, Model.TypeNames,"Select Moduletype", new{id = "ModuleList"})</div>
<br/>
<div id="partialDiv"></div>
</div>
<div class="form-actions" id="buttons">
<button type="submit" class="btn btn-primary" id="Submit">Save changes</button>
#Html.ActionLink("Cancel", "ModuleList", null, new { #class = "btn " })
</div>
}
</fieldset>
<div>
#Html.ActionLink("Back to List", "ModuleList")
</div>
<script>
$("#buttons").hide();
$("#ModuleList").on("change", function() {
var modId = $(this).val();
$.get('#Url.Action("GetModulePropertyName", "Module")', { moduleTypeValue: modId }, function(result) {
$("#partialDiv").html(result);
});
//uncomment following section to check if the partial view is working properly
/*.done(function() { alert("done"); })
.fail(function() { alert("fail"); })
.always(function() { alert("completed"); });*/
});
$("#buttons").show();
</script>
and here is the partial view
#model IEnumerable<string>
#foreach(var names in Model)
{
<div class="input-block-level">#Html.TextBoxFor(m=>names, new{Value="", placeholder=names})</div>
<br/>
}
Here is my model
public class CreateModule
{
//Empty form to handle form serialization
public CreateModule()
{
}
[Required]
public string ModuleId { get; set; }
[DataType(DataType.DateTime)]
public DateTime DateEntered { get; set; }
[Required]
public string SelectedModuleTypeName { get; set; }
public IEnumerable<SelectListItem> TypeNames { get; set; }
public List<Property> Properties { get; set; }
}
public class Property
{
public string Name { get; set; }
public string Value { get; set; }
}
Here is the method that script in main view forwards to
[HttpGet]
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
var modulePropertyNames = _repository.GetModuleKindPropertyNames(moduleTypeValue);
return PartialView("GetModulePropertyName",modulePropertyNames);
}
and finally here is httppost method for the main view
[HttpPost]
public ActionResult CreateModule(CreateModule moduleV)
{
var module = new Module
{
ModuleTypeId = Convert.ToInt64(moduleV.SelectedModuleTypeName),
ModuleId = moduleV.ModuleId,
DateEntered = moduleV.DateEntered,
};
if (ModelState.IsValid)
{
_repository.AddModule(module);
Success("Module added successfully!");
return RedirectToAction("ModuleList", "Module", new {area = "Hardware"});
}
Error("Something went wrong!");
return RedirectToAction("CreateModule", "Module", new { area = "Hardware" });
}
Current situation:
When the form is posted, the properties value of the model that is being passed via partial view is null. I get other values, like typename, Module ID.
What I'd want:
I also want to get the value of properties that is being passed via partial view.
You don't have any input field for the Properties property anywhere in your form. So it will always be null. That's normal.
Here's how you could proceed. Start by setting the correct navigational property so that the helper generates correct names of the corresponding input fields.
Also make sure that you are passing an IEnumerable<Property> model to the partial if you want to be able to get them back correctly:
[HttpGet]
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
IList<Property> model = ...
return PartialView("GetModulePropertyName", model.ToList());
}
and in your partial view use an editor template:
#model IList<Property>
#{
// This indicates the current navigational context to the helpers
ViewData.TemplateInfo.HtmlFieldPrefix = "Properties";
}
#Html.EditorForModel()
and the last step is to define a custom editor template for the Property class: ~/Views/Shared/EditorTemplates/Property.cshtml (note that the name and location of the template is important)
#model Property
<div class="input-block-level">
#Html.HiddenFor(m => m.Name)
#Html.TextBoxFor(m => m.Value, new { placeholder = Model.Name })
</div>
<br />
Try using the
List<Property>
as a model in your partial view and pass the CreateModule.Properties as model from your View
The problem is model binder can not figure out there
#Html.TextBoxFor(m=>names, new{Value="", placeholder=names})
belongs to as the "names" is not a property on your model class. If you need to bind to the CreateModule.Properties you need to change the partial view to emit textboxes with aproprate names, like this one:
#model IEnumerable<string>
#
{
int i=0;
}
#foreach(var names in Model)
{
<div class="input-block-level">#Html.TextBox("Properties[" + i + "].Value")</div>
<br/>
}

how to add some own forms in a ASP.NET MVC create view?

i have a problem, i had created a controller and a view for adding a new item from a specific model. the view looks like:
#modelModels.UserItem
#{
ViewBag.Title = "New";
}
<h2>New</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Device</legend>
<div class="editor-label">
#Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.name)
#Html.ValidationMessageFor(model => model.name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and the controller:
[HttpPost]
public ActionResult New(UserItem useritem)
{
if (ModelState.IsValid)
{
db.UserItems.AddObject(useritem);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(useritems);
}
how i want to add a dropdown to the form in the view like this:
<select id="Select1">
<option>MARS</option>
</select>
how to access the data from the form after it was submitted in the controller?
Have view model for your page,this view model will be used in your view. So, only include fields from your model that you really need. In Get action you should create this view model and get the needed properties from your model and map them to your view model.
public class UserItemViewModel
{
/* Properties you want from your model */
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
/* Property to keep selected item */
public string SelectedItem { get; set; }
/* Set of items to fill dropdown */
public IEnumerable<SelectListItem> SelectOptions { get; set; }
/* Fill the SelectListHere. This will be called from index controller */
public void FillOptions()
{
var items = new[] { "Mars", "Venus" }.
Select(x => new SelectListItem { Value = x, Text = x });
SelectOptions= new SelectList(items, "Value", "Text");
}
}
Change controller for receiving ViewModel instead of Model itself.
[HttpPost]
public ActionResult New(UserItemViewModel useritem)
{
/* Repopulate the dropdown, since the values are not posted with model. */
userItem.FillOptions();
if (ModelState.IsValid)
{
/* Create your actual model and add it to db */
// TODO: Map your properties from model to view model.
// Let's say you created a model with name userItemModel
db.UserItems.AddObject(userItemModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(useritem);
}
You might need to change Index view controller little.(to fill dropdown)
[HttpGet]
public ActionResult Index()
{
/* Create new viewmodel fill the dropdown and pass it to view */
var viewModel = new UserItemViewModel();
viewModel.FillOptitons();
//TODO : From your model fill the required properties in view model as I mention.
return View(viewModel);
}
And your view,
/* Strongly typed view with viewmodel instead of model itself */
#modelModels.UserItemViewModel
/* This is the dropdown */
#Html.DropDownListFor(m => m.SelectedItem, Model.SelectOptions)
Add that property to your model
Use builtin EditorFor(preffered) or hand-written html to generate client-side input for that property.
Access submitted value by inspecting that property when user submits the form
I like emre's proposition of having a viewModel and I think is the Best solution to your question however just in case you don't want to go that way (you must have a really good reason because it is best) and still want a way to access the values of a form directly you can always use:
var x = Request["myFiledName"];
inside your controller to get to the values passed by your form.

Need help in Html.ListBox in ASP.NET MVC

I am presently working on a application in which I have a display a list of items in a list box in the view and then send back the selected items to the controller.
My model is as follows:
public class Items
{
[DisplayName("Items")]
public string[] Items { get; set; }
}
When the user first requests the page, the list of items has to be queried from a database and sent to the view.
I am able to figure out how to collect the items into ArrayList/string[] at the controller side but am not able to understand the syntax for binding the view with the model and displaying the list using Html.ListboxFor and sending back the model on form submit.
Can someone please help me.
Thanks.
View model:
public class MyViewModel
{
[DisplayName("Items")]
public string[] SelectedItemIds { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// preselect some items
// leave empty if you want none to be selected initially
SelectedItemIds = new[] { "1", "3" },
// Normally you would fetch those from your database
// hardcoded here for the purpose of the post
Items = Enumerable.Range(1, 10).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = " item " + x
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(string[] selectedItemIds)
{
// here you will get the list of selected item ids
// where you could process them
// If you need to redisplay the same view make sure that
// you refetch the model items once again from the database
...
}
}
View (Razor):
#model AppName.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.SelectedItemIds)
#Html.ListBoxFor(
x => x.SelectedItemIds,
new SelectList(Model.Items, "Value", "Text")
)
<input type="submit" value="OK" />
}
View (WebForms):
<% using (Html.BeginForm()) { %>
<%= Html.LabelFor(x => x.SelectedItemIds) %>
<%= Html.ListBoxFor(
x => x.SelectedItemIds,
new SelectList(Model.Items, "Value", "Text")
) %>
<input type="submit" value="OK" />
<% } %>

Resources