ASP MVC 3 Display List<> Name - asp.net-mvc

i have this model
public class Registro
{
[DisplayName("Provincia")]
[Required]
public int ProvinciaID { get; set; }
public List<Provincia> rProvincia { get; set; }
}
Now what i need to do for show the Name of List<Provincia> rProvincia in my detalis view?, i was thinking that maybe #Html.DisplayFor(modelItem => item.rProvincia.Name), any idea?,
Thanks guys :)

No need to write any foreach loops. In your main view simply:
#model AppName.Models.Registro
...
#Html.DisplayFor(x => x.rProvincia)
...
and then inside the display template ~/Views/Shared/DisplayTemplates/Provincia.cshtml:
#model AppName.Models.Provincia
<div>
#Html.DisplayFor(x => x.Name)
</div>
This display template will be rendered for each item in the rProvincia collection.

FIX:
public class Registro
{
[DisplayName("Provincia")]
[Required]
public int ProvinciaID { get; set; }
public virtual Provincia rProvincia { get; set; }
}
with virtual i got it

Related

How to bind one model for creating dropdownlist and second model for textboxes using strongly typed view in MVC?

1st model:
public class VehicleMake
{
[Key]
public int MakeId { get; set; }
public string Make { get; set; }
}
2nd Model:
public class VehicleModel
{
[Key]
public int ModelId { get; set; }
public string Model { get; set; }
public DateTime Year { get; set; }
public int MakeId { get; set; }
public VehicleMake VehcileMake { get; set; }
}
How to pass two models as strongly typed view.
my view has 1) one dropdownlist which bind make and makeid from VehicleMake class
2) one textbox as Model which binds from vehicleModle class
Please suggest how to create a view using multiple models?
#model MvcApplication1.Data.ViewVMModel
....
<h2>CreateModel</h2>
<table>
<tr>
<td>#Html.Label("Select Make")</td>
<td>#Html.DropDownListFor(model=>model.VehicleMake,new SelectList(Model. "MakeId","Make")))</td>
</tr>
<tr>
<td>Enter Model </td>
<td>#Html.TextBoxFor(model=>model.VehcileModel)</td>
</tr>
</table>
You're editing data so first step is to create a view model (add other validation attributes as required).
public class VehicleVM
{
[Required(ErrorMessage = "...")]
public string Model { get; set; }
[Required(ErrorMessage = "...")]
public DateTime? Year { get; set; } // make nullable to protect against under-posting attacks
[Required(ErrorMessage = "...")]
[Display(Name = "Make")]
public int? SelectedMake { get; set; }
public IEnumerable<SelectListItem? MakesList { get; set; }
}
and in the GET method, initialize an instance of your view model, populate it and pass it to the view
var makes = db.VehicleMakes; // get the Makes from the database
VehicleVM vehicle = new VehicleVM()
{
MakesList = new SelectList(makes, "MakeId", "Make")
};
return View(vehicle);
and in the view
#model VehicleVM
....
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.SelectedMake)
#Html.DropDownListFor(m => m.SelectedMake, Model.MakesList)
#Html.ValidationMessageFor(m => m.SelectedMake)
#Html.LabelFor(m => m.Model)
#Html.TextBoxFor(m => m.Model)
#Html.ValidationMessageFor(m => m.Model)
....
Which will post back to
public ActionResult Create(VehicleVM vehicle)
your Viewmodel should be something like this
public VehicleModel VehicleModel { get; set; }
public List<VehicleMake> VehcileMakeList { get; set; }
and in your view
#model MvcApplication1.Data.ViewVMModel
....
<h2>CreateModel</h2>
<table>
<tr>
<td>#Html.Label("Select Make")</td>
<td>#Html.DropDownListFor(model=>model.VehicleModel.MakeId ,new SelectList(Model.VehcileMakeList, "MakeId","Make")))</td>
</tr>
<tr>
<td>Enter Model </td>
<td>#Html.TextBoxFor(model=>model.VehcileModel.Model)</td>
<td>#Html.TextBoxFor(model=>model.VehcileModel.Year )</td>
</tr>
</table>
and in your action
ViewVMModel vm = new ViewVMModel();
vm.VehcileMakeList = //get list of make
vm.VehicleModel = new VehicleModel();
return view(vm);

Display UserName and Role in MVC4

I want to create an easy Admin panel for editing users roles. First I want to display users list with their roles.
First I edited some things in AccountModel:
Context:
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<UserRole> UserRole { get; set; }
}
User profile:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailId { get; set; }
public string Details { get; set; }
public virtual ICollection<UserRole> UserRole { get; set; }
}
User roles:
[Table("webpages_Roles")]
public class UserRole
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserProfile> UserProfile { get; set; }
}
After that I created UserController with ActionResult Index:
public ActionResult Index()
{
using (var db = new UsersContext())
{
return View(db.UserProfiles.Include("UserRole").ToList());
}
}
And View:
#model IEnumerable<AnimeWeb.Models.UserProfile>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
User Name
</th>
<th>
User Role
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserRole)
</td>
</tr>
}
Partial View for UserRole looks like this:
#model AnimeWeb.Models.UserRole
<tr>
#Html.DisplayFor(model => model.RoleName),
</tr>
When I try to execute it I get InnerException error: "Invalid object name 'dbo.UserRoleUserProfiles'.". I dont quite get it. Could someone explain me why is this happening and how to resolve this?
Seems like the problem lies here
public virtual ICollection<UserRole> UserRole { get; set; }
And you don't have a mapping for these classes, so the default setting creates a UserRoleUserProfiles table(or class) and it doesn't exist in the database, so the problem occurs.
You can try remove this line of code and then try run the project again

kendo multiselect, send selected values to controller

I'm new to ASP.NET mvc and kendo ui framework and have the following issue:
I have a partialview in a window with a multiselect which receives its values out of the database. the view looks like:
#model SoftwareAdminInterface.Models.Administration.Pattern
<div id="myContentPopupEditRole_div">
#using (Ajax.BeginForm("SetCombi", "Pattern", new { }, new AjaxOptions() { HttpMethod = "post", UpdateTargetId = "myContentPopupEditRole_div" }))
{
<center>
<br />
<table class="table_no_borders">
<tr>
<td style="width: 300px">
#(
Html.Kendo().MultiSelectFor(model => model.RegExId)
.MaxSelectedItems(2)
.Name("RegExID")
.DataTextField("RegExName")
.DataValueField("RegExID")
.Placeholder("Select Patterns...")
.AutoBind(false)
.DataSource(source => {
source.Read(read =>
{
read.Action("GetPatternsForCombi", "Pattern");
})
.ServerFiltering(true);
})
)
</td>
</tr>
</table>
<button class="k-button k-button-icontext k-grid-custom" id="get" type="submit">#Resources.General.BtnSave</button>
</center>
}
</div>
I'm using a model which looks like this:
public class Pattern
{
[ScaffoldColumn(false)]
public int RegExID { get; set; }
[Display(Name = "RegEx")]
[Required]
public string RegExName { get; set; }
[UIHint("GridForeignKey")]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string ColumnName { get; set; }
public string RegExTable { get; set; }
[UIHint("GridForeignKey")]
public int? TableID { get; set; }
public string Version { get; set; }
public string Description { get; set;
}
in the SetCombi function which is called in the patterncontroller, I only want to receive the two ID's of the selected objects out of the multiselect, but I've no idea how they should be send to the controller.
thx in advance for your help
I think you have two options:
1) Change RegExID to be a string and then I believe they would come across as comma separated values.
2) (The better option) Add a ViewModel which has many of the same properties as your Pattern model above. The main difference for this is that you would have
public List<int> RegExIDs { get; set; }
Then in your controller you would take the new ViewModel as an argument to your post method and parse out the values in the list as necessary.

mvc model validation required not working on all fields

I'm working in ASP.NET MVC 4 and I have the problem that my model validation isn't working correctly. For some reason not all my required fields have to be filled in.
Here's my model:
public class MovieModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
[Required]
public string Genre { get; set; }
[Required]
public decimal Price { get; set; }
public virtual ICollection<RoleInMovie> RoleInMovie { get; set; }
}
Here's the View:
#using (Html.BeginForm())
{
<table>
<tr>
<td>
<label>Name:</label></td>
<td>#Html.EditorFor(m => m.Name)</td>
<td>#Html.ValidationMessageFor(m => m.Name)</td>
</tr>
<tr>
<td>
<label>Genre:</label></td>
<td>#Html.EditorFor(m => m.Genre)</td>
<td>#Html.ValidationMessageFor(m => m.Genre)</td>
</tr>
<tr>
<td>
<label>Price:</label></td>
<td>#Html.EditorFor(m => m.Price)</td>
<td>#Html.ValidationMessageFor(m => m.Price)</td>
</tr>
</table>
<button type="submit">Submit</button>
}
And here's my action:
[HttpPost]
public ActionResult Add(MovieModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View();
}
Now here's the thing: as soon as I enter only a price, modelstate.isvalid becomes true. When hovering over my model, it sais both name and genre are null. Ofcourse they are required, but the validation doesn't work.
Also, the validationmessagefor only works on price.
I hope I'm not overlooking something too ridiculous. Thanks for the help!
Return the invalid model back to the view:
[HttpPost]
public ActionResult Add(MovieModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(model); // <----
}
Oh, and make sure that the required attribute is disallowing empty strings
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.allowemptystrings.aspx
public class MovieModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
[Required(AllowEmptyStrings = false)]
public string Genre { get; set; }
[Required]
public decimal Price { get; set; }
public virtual ICollection<RoleInMovie> RoleInMovie { get; set; }
}

Populate List<Objects> From Mvc 3 view

I Have a Viewmodel based on Nominees . And i can have Multiple Nominees for the viewmodel.
I want to populate the Ilist From the view . Here are my viewmodels
public class DebitViewModel:IValidatableObject
{
public string AgentName { get; set; }
public Debit Debit { get; set; }
public Policy Policy { get; set; }
public PolicyType PolicyType { get; set; }
public Customer Customer { get; set; }
public IList<PolicyType> PolicyTypes { get; set; }
public List<Nominee> Nominees { get; set; }
public Dictionary<int,string> OccupationTypes { get; set; }
}
I want to populate all Nominess automatically when i press submit . so how should i create by view and make it automatically populate List automatically ? instead of serparate objects ?
You could use editor templates:
#model DebitViewModel
#using (Html.BeginForm())
{
... some input fields for the other properties that we are not interested in
#Html.EditorFor(x => x.Nominees)
<button type="submit">OK</button>
}
and then you define a custom editor template for the Nominee model (~/Views/Shared/EditorTemplates/Nominee.cshtml) which will automatically be rendered for each element of the Nominees collection:
#model Nominee
<div>
#Html.EditorFor(x => x.FirstName)
#Html.EditorFor(x => x.LastName)
...
</div>
say for example the Nominee looks like
public class Nominee{
public int Id{get;set;}
public string Name{get;set;}
public int Age {get;set;}
}
the view would look like
#for (int i = 0; i < Model.Nominees.Count(); i++)
{
<tr>
<td>#Html.TextBoxFor(m => m.Nominees[i].Name)</td>
<td>#Html.TextBoxFor(m => m.Nominees[i].Age)</td>
</tr>
}
read more about model binding to a list

Resources