Html.DropDownList razor - asp.net

I'm new to MVC and C# and having hard time with a dropdown list.
What I'm trying to accomplish is to initialize my page with an object that keeps the settings.
(I read settings from XML file).
Here's what I have
public class StoreSettings
{
public String BackSrs2Path { get; set; }
public int NoLines { get; set; }
public String Requesturl { get; set; }
}
public class Store
{
public String StoreId { get; set; }
public String Address { get; set; }
public StoreSettings StoreSettings { get; set; }
}
and the Model for my view page is a list of Store
#model System.Collections.Generic.List<Control2.Models.Store>
#{
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (var Store in Model)
{
SelectListItem i = new SelectListItem();
i.Text = Store.StoreId;
i.Value = Store.StoreId;
selectList.Add(i);
}
}
#using (Html.BeginForm())
{
SelectList list = new SelectList(selectList, "Value", "Text");
#Html.DropDownList("ddl", list, "select store", new { onchange = "this.form.submit();" });
}
}
By reading examples here managed to populate the dropdownlist from my model and postsback
but now i need to get only the selected object from the list and apply his seetings to the page to display it etc a message "you ve selected Store"+Storeid(the slected from dropdown)
Also this code is written in my cshtml page which isn't the best but couldn't figure how should I do it with ViewModel and dropdown list

Yes when I first started looking at the DropDownList Binding mechanisms of MVC I too had problems. What I'd like to do is suggest to you the following:
Create a Viewmodel and bind the entire view to the viewmodel... as follows:
public class VMStore
{
public VMStore()
{
ItemsInDropDown = new List<SelectListItem>(){
new SelectListItem{ Text="SomeValue", Selected=false, Value="SomeUniqueId"}
};
}
public String StoreId { get; set; }
public String Address { get; set; }
public StoreSettings StoreSettings { get; set; }
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> ItemsInDropDown { get; set; }
public void Post()
{
//This method will have the user selected value...
}
}
The view will bind fields like this:
#model WebApplication1.ViewModels.VMStore
#{
ViewBag.Title = "GetStore";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetStore</h2>
<div>
<h4>VMStore</h4>
<hr />
<dl class="dl-horizontal">
#Html.BeginForm(){
<dt>Select Store</dt>
<dd>#Html.DropDownListFor(p=>Model.SelectedValue, Model.ItemsInDropDown) </dd>
<dd><button type="submit">Submit</button></dd>
}
</dl>
</div>
The action methods will look like this:
public ActionResult GetStore()
{
return View();
}
[HttpPost]
public ActionResult GetStore(ViewModels.VMStore userdata) {
if (ModelState.IsValid)
{
userdata.Post();
}
return View(userdata);
}

Related

View Modeling: List field

I have a Form class that has a List<FormField>.
public class Form
{
public int ID { get; set; }
public int templateID { get; set; }
public List<FormField> fields { get; set; }
public Form()
{
fields = new List<FormField>();
}
}
The FormField:
public class FormField
{
public object value { get; set; }
public TemplateField templateField {get;set;}
}
And the TemplateField:
public class TemplateField
{
public int ID { get; set; }
public string fieldDescription { get; set; }
public TemplateFieldType type { get; set; }
}
My controller class:
public class MedicalAppointment : Controller
{
public IActionResult Index()
{
Template template = new TemplateDataMapper().GetMedicalAppointmentTemplate();
Form form = new Form();
form.templateID = template.ID;
foreach(TemplateField field in template.fields)
{
FormField formField = new FormField();
formField.templateField = field;
form.fields.Add(formField);
}
return View(form);
}
public IActionResult TemplateManagement()
{
return View();
}
[HttpPost]
public void SaveForm(Form form)
{
......
}
My view looks like this:
#model Form
....
#using (Html.BeginForm("SaveForm", "MedicalAppointment", FormMethod.Post, new { id = "registerDonorForm" }))
{
<table class="personal-data">
#for(int i=0; i<Model.fields.Count; i++)
{
<tr>
<th>#Html.LabelFor(model => Model.fields[i].templateField.ID, Model.fields[i].templateField.fieldDescription)</th>
<th>#Html.TextBoxFor(model => Model.fields[i].value)</th>
</tr>
}
</table>
<div class="register-button">
<input type="submit" value="Registar" />
</div>
}
</div>
I want to create a dynamic form, where when I submit it, I could receive a Form with the field[i].value.
My problem is that, when I submit the form, in the controller, I don't receive any value submitted by the user. The Form is received with the FormField.Value null as well the Form.FormField.TemplateField.ID.
Any one can help me with that?
Note: Forget the class names on html and other wrong names.
Thank you in advance

Get DropDownListFor selected value in multiple model

I create multiple model
public class MultipleModel
{
public Photo Photo { get; set; }
public Room Room { get; set; }
}
for two different models:
public class Room
{
public int Id { get; set; }
public string NumberRoom { get; set; }
public virtual ICollection<Photo> Photo { get; set; }
}
public class Photo
{
public int Id { get; set; }
public string PhotoName { get; set; }
public int Roomid { get; set; }
public virtual Room Room { get; set; }
}
On click Submit in my view i want upload image to the folder with the name from DropDownListFor selected item ( for example /images/2/, where 2=id from DropDownListFor) and add to database. How i can correctly send selected item from DropDownListFor using Html.BeginForm?
My view:
#using Hotel.BusinessObject
#model MultipleModel
#using (Html.BeginForm("AddRoomImg", "Admin",
FormMethod.Post, new { enctype = "multipart/form-data", id = Model.Room.Id}))
{
<div>#Html.DropDownListFor(m=> m.Room.Id, ViewBag.roomlist as SelectList, "Select Room")</div>
<input type="file" name="img" />
<input type="submit" value="upload" />
}
And my controller, where Room.Id in formCollection is always=0 and int? id not works and return NULL
public ActionResult AddRoomImg()
{
ViewBag.roomlist = new SelectList(db.Room, "Id", "NumberRoom");
return View();
}
[HttpPost]
public ActionResult AddRoomImg(FormCollection formCollection, int? id)
{
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
if (file.ContentLength > 0)
{
ImageUpload imageUpload = new ImageUpload { Width = 600 };
ImageResult imageResult = imageUpload.RenameUploadFile(file);
if (imageResult.Success)
{
//TODO: write the filename to the db
}
else
{
ViewBag.Error = imageResult.ErrorMessage;
}
}
}
Try this
[HttpPost]
public ActionResult AddRoomImg(MultipleModel model, HttpPostedFileBase img)
{
//your code here
}
or
[HttpPost]
public ActionResult AddRoomImg(MultipleModel model)
{
var image = Request.Files(0); //access your images
//rest of your code here
}
As your question is about getting selected value from dropdownListFor into the MultipleModel, first of all you should update your function parameters.
use MultipleModel model to get the form data into model andHttpPostedFileBase img instead of FormCollection formCollection to get the image file as object. try the following way.
[HttpPost]
public ActionResult AddRoomImg(MultipleModel model, HttpPostedFileBase img)
{
// To get the selected value from dropdownListFor
var selectedRoomId = model.Room.Id;
// do what you want to do with img object
// you will get img.name in the file object that you can rename
}

DropdownList selected value not saved in database

I need big help from here i am new to Asp.net MVC 4 Application development , actually i faced a problem when i save my dropdownlist selected value in a database ,after i click my submit button.
I use Debug pointer to check values in a HTTP post object but it doesn't contain dropdownlist select value it always display null value in a division raw I need some expert advice to solve that problem i go through the several examples and try several times but still i haven't proper solution for that.
Model class:
public partial class tblEmployee
{
public int EmployeeId { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public Nullable<System.DateTime> DateOfJoin { get; set; }
public string Position { get; set; }
public string Office { get; set; }
public string Division { get; set; }
public Nullable<decimal> Salary { get; set; }
public virtual tblDivision Divisions { get; set; }
}
public partial class tblDivision
{
public int value { get; set; }
public string Division { get; set; }
public Nullable<int> SelectId { get; set; }
}
Controller class:
namespace EmpiteHrSystem.Controllers
{
public class EmployeeController : Controller
{
private EmpiteContext db = new EmpiteContext();
public ActionResult Create()
{
ViewBag.DivisionOptions = new SelectList(db.tblDivisions, "value","Division");
return View();
}
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(tblEmployee tblemployee)
{
if (ModelState.IsValid)
{
try
{
db.Entry(tblemployee).State = EntityState.Added;
db.tblEmployees.Add(tblemployee);
db.SaveChanges();
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
}
}
}
View:
#model EmpiteHrSystem.Models.tblEmployee
#{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml";}
#Html.EditorFor(model => model.EmployeeId)
#Html.ValidationMessageFor(model => model.EmployeeId)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#*#Html.EditorFor(model => model.Office)*#
#Html.DropDownList("DivisionOptions")
#Html.ValidationMessageFor(model => model.Division)
#Html.ActionLink("Back to List", "Index")
Your DivisionOptions drop down list is not being bound back to the model properly because it is the wrong name. Your model is looking for a property with the name Division while your drop down list is being bound to DivisionOptions. You have a few options.
Use a strongly typed helper
#Html.DropDownListFor(x=>x.Division, (SelectList)ViewBag.DivisionOptions)
Rename your currrent code and pass in the SelectList
#Html.DropDownList("Division", (SelectList)ViewBag.DivisionOptions)

ASP.NET MVC 3 Model null on submit

View
#model Survey.Models.TakeSurveyViewModel
#{
Layout = "~/Views/Shared/_SiteLayout.cshtml";
}
<h2>SURVEY : #Model.Title</h2>
<h3>#Model.Description</h3>
<hr />
#using (Html.BeginForm("SubmitSurvey", "HomePage", FormMethod.Post, new { id = "surveyForm" }))
{
for (int index = 0; index < Model.SurveyQuestions.Count; index++)
{
#* Editor Template - Null result *#
#*SurveyQuestionModel item = Model.SurveyQuestions[index];
#Html.EditorFor(x => item);*#
<p>#Model.SurveyQuestions[index].QuestionText</p>
#Html.DropDownListFor(item => Model.SurveyQuestions[index].OptionId, new SelectList(Model.SurveyQuestions[index].Options, "OptionId", "OptionText"), string.Empty)
}
<input type="submit" value="SubmitSurvey" />
}
ViewModel
public class TakeSurveyViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public int SurveyId { get; set; }
public List<SurveyQuestionModel> SurveyQuestions { get; set; }
public TakeSurveyViewModel() { }
public TakeSurveyViewModel(int surveyId)
{
//Populate data - works ok.
}
}
DropDownList Model
public class SurveyQuestionModel
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
[Required(ErrorMessage = "Please select an option.")]
public int OptionId { get; set; }
public IEnumerable<QuestionOption> Options { get; set; }
}
The page is rendering fine, with all the drop-downs with correct options. The id and name of each select is also unique -
id="SurveyQuestions_3__OptionId" name="SurveyQuestions[3].OptionId"
Controller Action
[HttpPost]
public ActionResult SubmitSurvey(TakeSurveyViewModel model)
{
return !ModelState.IsValid ? TakeSurvey(model.SurveyId) : null;
}
But clicking on the submit button, controller action model is null.
Edit: Removed the 2x HTML.BeginForm
Edit 2: SurveyQuestions now has public setter. The issue seem to be still there. Please see this image:
Is the problem that you have SurveyQuestions being a private set?
-old answer-
You have 2 x
(Html.BeginForm(Html.BeginForm
I once forgot to have my form within a using statement which did the same sort of thing.

Drop down list access data from database table stored in App_DA\ata

this is my model class
public class Model1
{
public string popcorn { get; set; }
public string pselectedItem { get; set; }
public IEnumerable items { get; set; }
}
this is my controller class:-
public class HomeController : Controller
{
private rikuEntities rk = new rikuEntities();
public ActionResult Index()
{
var model = new Model1
{
items = new[]
{
new SelectList(rk.emp,"Id","name")
}
}; return View(model);
}
public ActionResult viewToController(Model1 m)
{
string getSelectedName = m.popcorn;
return Content(getSelectedName);
}
}
this is my view;-
#model chetan.Models.Model1
#using (Html.BeginForm("viewToController", "Home"))
{
#Html.ValidationSummary(true)
emp
<div class="editor-field">
#Html.DropDownListFor(x => x.popcorn, new SelectList(Model.items))
</div>
</fieldset>
}
in my example i want to get values in Dropdownlist from database table named "emp" and after select a element of dropdownlist i want to use that element in Index action of Home controller. please check my code carefully and let me know what should i do ?
First in your model your model you need SelectList and not IEnumerable<SelectList>:
public class Model1
{
public string popcorn { get; set; }
public string pselectedItem { get; set; }
public SelectList items { get; set; }
}
and then in your view:
#Html.DropDownListFor(x => x.popcorn, Model.items)
The rest of your code seems fine.

Resources