Get DropDownListFor selected value in multiple model - asp.net

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
}

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

Html.DropDownList razor

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

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.

MVC3 (Razor) Passing Model Data

I'm making Memo web application.
and the main page contain 'Create and List and Modify' functions.
But I don't know how to pass Model (for create) and List (for List) to View(Razor) from controller.
this is my note model,
[Table("note")]
public class Note
{
[Key]
public int id { get; set; }
[Required(ErrorMessage="Content is required")]
[DisplayName("Note")]
public string content { get; set; }
public DateTime date { get; set; }
[Required(ErrorMessage = "User ID is required")]
[DisplayName("User ID")]
public string userId {get; set;}
public Boolean isPrivate { get; set; }
public virtual ICollection<AttachedFile> AttachedFiles { get; set; }
}
I tried,
1)
public ActionResult Index()
{
var notes = unitOfWork.NoteRepository.GetNotes();
return View(notes);
}
Then, in view,
#model Enumerable<MemoBoard.Models.Note>
//I can not use this, because the model is Enumerable type
#Html.LabelFor(model => model.userId)
So, I made viewModel
2)
public class NoteViewModel
{
public IEnumerable<Note> noteList { get; set; }
public Note note { get; set; }
}
In Controller,
public ActionResult Index()
{
var notes = unitOfWork.NoteRepository.GetNotes();
return View(new NoteViewModel(){noteList=notes.ToList(), note = new Note()});
}
and In View,
#model MemoBoard.Models.NoteViewModel
#Html.LabelFor(model => model.note.userId)
it looks well, BUT in source view, it's showing
<input data-val="true" data-val-required="User ID is required" id="note_userId" name="note.userId" type="text" value="" />
the name is note.userId not userId.
List this case, how should I do to make working?
Please advice me.
Thanks
[EDIT]
(First of all, thanks for all advices)
Then, How can I change this controller
[HttpPost]
public ActionResult Index(Note note)
{
try
{
if (ModelState.IsValid)
{
unitOfWork.NoteRepository.InsertNote(note);
unitOfWork.Save();
return RedirectToAction("Index");
}
}catch(DataException){
ModelState.AddModelError("", "Unable to save changes. Try again please");
}
return RedirectToAction("Index");
}
If I change parameter type to NoteViewModel, then how should I do for valid check?
[HttpPost]
public ActionResult Index(NoteViewModel data)
{
try
{
if (ModelState.IsValid) <===
#model Enumerable<MemoBoard.Models.Note>
//I can not use this, because the model is Enumerable type
#Html.LabelFor(model => model.userId)
You can use it in foreach loop or return list and use it in for loop
the name is note.userId not userId.
It's normal, this made for model binding
Try this:
Html.TextBox("userId", Model.note.userId, att)

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