asp .net mvc 4 dropdownlist - asp.net

I am using VS2012 MVC 4 with EF. I want to make a view where the user can upload movie title and type for it (actionmovie, scifi, etc that comes from a dropdownlist!), and store it in database.
Model:
public class Movie
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Type")]
public int TypeId { get; set; }
public virtual Type Type { get; set; }
}
public class Type
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TypeId { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Movie> Movies { get; set; }
}
If I am right I successfully made One to Many relationship between the Type and Movie table.
Controller:
[HttpPost]
[Authorize]
public ActionResult NewMovie(Movie movie)
{
db.Movies.Add(movie);
db.SaveChanges();
return View(movie);
}
View:
#using (Html.BeginForm())
{
<table>
<tr>
<td>#Html.DisplayNameFor(model => model.Name)</td>
<td>#Html.DisplayNameFor(model => model.TypeId)</td>
</tr>
<tr>
<td>#Html.TextBoxFor(model => model.Name)</td>
<td>#Html.DropDownListFor.........
</tr>
</table>
<input type="submit" value="submit" />
}
I do not really know how should I make this Dropdownlist in the view, and make the specific details for it in the controller with the most secure way
(I think i should make a list/enumerable from the movie.typeid or the Type class)
I would be very glad if you could help me! Thank you

I use List for my dropdown list. to do it that way you can build the list like this on your controller
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in Movies){
ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
}
Movie.MovieList = ls;
you can only pass one model to the view. from your code you are passing the movie model so put
public List<SelectListItem> MovieList { get; set; }
in your model. Then on the view you can build your dropdownlist like this
#Html.DropDownListFor(x => x.Id, Model.MovieList)
Let me know if you have any questions.

Related

MVC 5 Model Child list can't render in Partial view

I am new to ASP.NET MVC 5.
On debug mode, I saw some values being looped to the partial view but in UI no values are being displayed.
My Model
public class Model
{
public int ID { get; set; }
public string UserID { get; set; }
public List<ReferenceModel> ReferenceModelList{ get; set; }
}
My Controller
public ActionResult GetModel(string dataobject, int id = 0)
{
Model model = new Model();
model = BL.GetModel(dataobject, id);
return PartialView("_ReferenceModelList", model);
}
ReferenceModelList(PartialView)
#model Web.Model.Model
#{
Layout = null;
}
#foreach (var menurefitem in Model.ReferenceModelList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => menurefitem.Code)
</td>
<td>
#Html.DisplayFor(modelItem => menurefitem.Description)
</td>
</tr>
}
Partial View Data in VS:
Please help.
You need to call the Controller method from you main UI like this
#{Html.RenderAction("GetModel","SAPSecurity");}
At first you should instantiate your list at the constructor of your class.I think your problem should be solved.
public class Model
{
public Model()
{
ReferenceModelList=new List<ReferenceModel>();
}
public int ID { get; set; }
public string UserID { get; set; }
public List<ReferenceModel> ReferenceModelList { get; set; }
}

The model item passed into the dictionary is of type 'System.Collections.Generic.List… in ASP.net MVC [duplicate]

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

Saving dropdown list value to database ASP.net 5.0 MVC 6 using tag helpers

I am trying to save my dropdown list values to my database in an ASP.NET web application using MVC6 and Entity Framework 7 but the values are not saving.
I have two classes one called expenses and when a user creates an expense they need to select a country. I have the country dropdown list populating but when the expense is saved the countryid is not being saved to the database.
Models
public class Country
{ public int Countryid { get; set; }
public string CountryCode { get; set; }
}
public class Expense
{
public int ExpenseId { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime ExpenseDate { get; set; }
public virtual Country Countryid { get; set; }
Expense Controller
private void PopulateCountriesDropDownList(object selectedCountry = null)
{
var list = _context.Countries.OrderBy(r => r.CountryCode).ToList().Select(rr =>
new SelectListItem { Value = rr.Countryid.ToString(), Text = rr.CountryCode }).ToList();
ViewBag.Countries = list;
}
// GET: Expenses/Create
public IActionResult Create()
{
PopulateCountriesDropDownList();
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Expense expense)
{
if (ModelState.IsValid)
{
_context.Expenses.Add(expense);
_context.SaveChanges();
return RedirectToAction("Index");
}
PopulateCountriesDropDownList(expense.Countryid);
return View(expense);
}
View
<div class="form-group">
<label asp-for="Countryid" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Countryid" class="form-control"asp-items=#ViewBag.Countries></select>
<span asp-validation-for="Countryid" class="text-danger" />
</div>
</div>
First of all the Countryid property in your Expense model is a of a complex type (Country). The model binder cannot map the posted Countryid form value to this Complex object.
You should add a CountryId property to your Expense model of type Int
public class Expense
{
public int ExpenseId { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime ExpenseDate { get; set; }
public int CountryId { set;get;}
public virtual Country Country { get; set; }
}
While this will fix the problem, A more better & clean solution is to use a view model for transferring data between your view and action method. With this approach your view is not tightly coupled to the entity classes generated by your ORM.
So create a view model for your view with properties absolutely needed for the view.
public class CreateExpenseVm
{
public List<SelectListItem> Countries { set;get;}
public int CountryId { set;get;}
//Add other properties, if your view need them.
}
and in your GET action, you create an object of this class, load the Countries collection property and send it to your view.
public ActionResult Create()
{
var vm=new CreateExpenseVm();
vm.Countries = _context.Countries.OrderBy(r => r.CountryCode)
.Select(x=>new SelectListItem { Value=x.CountryId.ToString(),
Text=x.CountryCode}).ToList();
return View(vm);
}
And in your view,which is strongly typed to our new viewmodel,
#model CreateExpenseVm
<form asp-controller="Expense" asp-action="Create">
<label>Select Country</label>
<select asp-for="CountryId" asp-items="#Model.Countries" >
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
and in your HttpPost action, Use CreateExpenseVm as the parameter type. When the form is submitted, the default model binder will be able to map the posted form data to the properties of this class object.
[HttpPost]
public ActionResult Create(CreateExpenseVm model)
{
var e=new Expense { CountryId=model.CountryId };
e.ExpenseDate = DateTime.Now;
dbContext.Expenses.Add(e);
dbContext.SaveChanges();
return RedirectToAction("Index");
}

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)

Two Models or One View?

I want to use two models in one View. Here is my code:
public class Users {
public int id { get; set; }
public string adSoyad { get; set; }
public string email { get; set; }
public int puan { get; set; }
}
public class admin {
public int id { get; set; }
public string name { get; set; }
}
public class mainmodel {
public Users Users { get; set; }
public admin admin { get; set; }
}
I can use it to delete, edit, and create views. But I get errors in my index view:
#model IEnumerable<donemProje.Models.mainmodel>
What can I do?
Edit--
i try this in index view
#model donemProje.Models.mainmodel
#foreach (var item in Model.Users)
{
<tr>
<td>
#Html.DisplayFor(modelItem =>item.adSoyad)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
and get this error
Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'donemProje.Models.Users' because 'donemProje.Models.Users' does not contain a public definition for 'GetEnumerator'
int this line
Line 34: #foreach (var item in Model.Users)
Your model in the view should be #model mainmodel
If you want to use two models in one view, you should use ViewModels (A class which consists of other classes which are used in view)
#model IEnumrable or you tried #model IeEnumrable<mainmodel> ? if you tried #model IEnumrable<mainmodel> than mainmodel have list of users and admin in it. but what i understand from your question i think the below words will help you.
You can try #model mainmodel and you can iterate through mainmodel using foreach loop.
foreach(var user in Model.Users)
{
// you code goes here..
}
and same thing for the admin if want to iterate through admin. else just use #Model.Admin.id

Resources