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
Related
This question already has answers here:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
(7 answers)
Closed 5 years ago.
I'm trying to Create Poll System but there some issue.
I have to classes generate it by ADO.NET Entity Framework
Second I create Repository class to work with it from my controller class
I create ActionResult Method in my PollController class that return All the Pool Questions from my DataBase.
I have one Particle View I create it to show the option for specific question
When I put this particle in my Index.cshtml it give me this error The model item passed into the dictionary is of type 'System.Collections.Generic.List
here is my code
Poll.cs
public partial class Poll
{
public Poll()
{
this.PollOptions = new HashSet<PollOption>();
}
public int PollID { get; set; }
public Nullable<System.DateTime> AddedDate { get; set; }
public string AddedBy { get; set; }
public string QuestionText { get; set; }
public bool IsCurrent { get; set; }
public bool IsArchived { get; set; }
public virtual ICollection<PollOption> PollOptions { get; set; }
}
PollOption.cs
public partial class PollOption
{
public int OptionID { get; set; }
public Nullable<System.DateTime> AddedDate { get; set; }
public string AddedBy { get; set; }
public string OptionText { get; set; }
public int PollID { get; set; }
public Nullable<int> Votes { get; set; }
public virtual Poll Poll { get; set; }
}
PollRepository.cs
public class PollRepository
{
private PollPlatFormEntities entities = new PollPlatFormEntities();
public IQueryable<Poll> GetPolls()
{
return entities.Polls;
}
public Poll GetPoll(int Id)
{
return entities.Polls.FirstOrDefault(p => p.PollID == Id);
}
public IQueryable<Poll> CurrentPoll()
{
return entities.Polls.Where(c => c.IsCurrent == true);
}
public PollOption GetPollOption(int Id)
{
return entities.PollOptions.FirstOrDefault(o => o.OptionID == Id);
}
PollController.cs
public class PollsController : Controller
{
PollRepository pollRepository = new PollRepository();
//
// GET: /Polls/
public ActionResult Index()
{
var polls = pollRepository.GetPolls().ToList();
return View(polls);
}
}
here is my index.cshtml View
#model IEnumerable<PollSystem.Models.Poll>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.Partial("PollItem")
</td>
</tr>
}
and lastly my Particle View
#model PollSystem.Models.Poll
<div id="poll-#Model.PollID" class="poll">
<h2>#Model.QuestionText</h2>
#using (Html.BeginForm(FormMethod.Post))
{
<ul class="poll-options">
#foreach (var option in Model.PollOptions)
{
<li class="option" id="option-#option.OptionID">
<input type="radio" id="option-#option.OptionID" value="#option.OptionID"/>
<label class="text" for="option-#option.OptionID">
#option.OptionText
</label>
</li>
}
</ul>
<button type="submit" name="poll-submit">Vote</button>
}
</div>
If you do not explicitly pass a model to the partial view, it will use the model of the parent view, from which the partial view is called. In your case, you are not passing any model to the partial view method call, hence it is using the model of the parent page which is IEnumerable<PollSystem.Models.Poll> as the model of the partial.
Use this overload of Partial method which takes the model of the partial view as the second parameter
public static MvcHtmlString Partial(
this HtmlHelper htmlHelper,
string partialViewName,
object model
)
So in your main view, you can pass the item variable to the Partial call
#model IEnumerable<PollSystem.Models.Poll>
#foreach (var item in Model) {
<tr>
<td>
#Html.Partial("PollItem",item)
</td>
</tr>
}
Please try
#model IEnumerable<PollSystem.Models.Poll>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.Partial("PollItem",item)
</td>
</tr>
}
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
}
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);
}
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.
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.