I'm attempting to learn ASP.net and Angular at the same time.
What I want to do is display a list of states (which is retrieved in from a database) in a drop down list using Angular. I can get the states to display in a table.
This is what I have:
My Controller function:
public ActionResult StateListDistinct()
{
var distinctStates = (from w in db.Addresses
select new { State =
w.address_state}).Distinct();
List<string> states = db.Addresses.Select(state => state.address_state).Distinct().ToList();
return View(states);
}
My current View:
#model List<String>
<table class="table">
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(model => item)
</td>
</tr>
}
</table>
What do I need to do to get a drop down populated using Angular?
You can visit the below link for learning dropdown binding using AngularJs
http://techbrij.com/angularjs-cascade-dropdownlist-asp-net-mvc
You can also visit this link
http://www.aspdotnet-suresh.com/2015/02/angularjs-bind-set-dropdownlist-value-text-using-ng-options-ng-repeat.html
Related
I am creating a view page where I need to display data and as well as a form to insert data. To insert data I have bootstrap modal. How can I bind my view page so that I can have data to display in the page as well as create form to insert data. I mean how can I bind my view to display data?
public ActionResult GetFirm()
{
return View(db.FirmModels.ToList());
}
My view page
#model models.FirmModel
// code for bootstrap modal
// code for data table
<table id="tblFirmData">
<thead>
<tr>
<th>Edit/Print</th>
<th style="visibility:hidden;">#Html.DisplayNameFor(model => model.FirmId)</th>
<th>NAME</th>
<th>CONTACT</th>
</tr>
</thead>
<tbody>
#foreach(var item in models)
{
int status = item.FirmRegistrationStatus;
}
</tbody>
</table>
When I do foreach(var item in models) getting error 'models' is a namespace but is used like a variable and when I do #foreach(var item in Model) I am getting error foreach statement cannot operate on variables of type 'FirmModel' because 'FirmModel' does not contain a public instance definition for 'GetEnumerator'.
How to solve this problem, shall I need to modify my GetFirm return method or need to change in view page?
Because of you pass a list to the view define you view model as:
#model IEnumerable<models.FirmModel>
The IEnumerable interface is implementing the GetEnumerator() method used to iterate through the collection.
Or:
#model IList<models.FirmModel>
The IList interface inherits the IEnumerable.
And correspondingly:
#foreach(var item in Model)
{
....
}
I have a registration form and a grid(table)for viewing all records..
but i dont know how to display from different action method
My code shown below
#using (Html.BeginForm("Create", "Bathrooms", FormMethod.Post))
{
#Html.LabelFor(model => model.BathRoomDetails)
#Html.TextBoxFor(model => model.BathRoomDetails)
<br/>
#Html.LabelFor(model => model.shortstring)
#Html.TextBoxFor(model => model.shortstring)
<br/>
<button type="submit" class="btn btn-primary"/> Create</button>
<button type="submit"> View All</button>
}
and my grid code
<table>
#foreach (var a in ViewBag.data as List<RealEstate.Models.BathRoomVM>)
{
<tr>
<td>#a.BathRoomDetails</td>
<td>#a.BActive</td>
</tr>
}
</table>
and my controller
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(BathRoomVM Bathrooms)
{
ModelState.Clear();
var realContext = new RealEstateDBContext();
Bathroom Bathroomobj = new Bathroom();
Bathroomobj.BathRoomDetails = Bathrooms.BathRoomDetails;
Bathroomobj.shortstring = Bathrooms.shortstring;
realContext.Bathrooms.Add(Bathroomobj);
realContext.SaveChanges();
ModelState.Clear();
return View();
}
public ActionResult Get()
{
var realContext = new RealEstateDBContext();
var rslt = (from bathroom in realContext.Bathrooms
select new BathRoomVM { BathRoomDetails = bathroom.BathRoomDetails, BActive = bathroom.BActive, Bcancelled = bathroom.Bcancelled }).Where(m => m.BActive == true && m.Bcancelled == false).ToList();
ViewBag.data = rslt;
return View();
}
I need To Load or Display Grid Only after click ViewAll Button .. I already try different ways but none of them worked .. Please help me how to implement , i have stuck in this problem from last 2 days..
I have use
public ActionResult Create()
{
var realContext = new RealEstateDBContext();
var rslt = (from bathroom in realContext.Bathrooms
select new BathRoomVM { BathRoomDetails = bathroom.BathRoomDetails, BActive = bathroom.BActive, Bcancelled = bathroom.Bcancelled }).Where(m => m.BActive == true && m.Bcancelled == false).ToList();
ViewBag.data = rslt;
return View();
}
I got result in this way , too slow (more time required to search data from db ) ..
[ I need to call a other action method and create a list in my view ]
You really need to get away from using viewbag. It's a clear sign that you not comfortable using view models. With that said, your going to need to use jQuery, a view model and a partial view.'
Here are the pieces:
1. Replace your table area is a div that will then hold your table that will be returned from a partial view.
Create a partial view .cshtml file that contains your table logic and uses a view model that will also be returned from your partial view controller action.
You'll need to assign a click event with a prevent default action on your submit button to prevent it from submitting the page but instead to call the partial view controller action to update the table area.
If I had some clarity I might be able to help a little more. When you click Create, do you want it to update the table or only when you click view all?
A couple other thoughts. You could use jQuery to add a new row in your table each time you create and then use an jQuery ajax call to send the bathroom data to the server.
Another feature that might be helpful is to use a MemoryCache. It's fairly easy to implement but you would need to reset it each time you add a new bathroom otherwise you'll not get an updated list.
If you need something specific, let me know.
I am generally new to ASP.NET and am modifying some code that I've inherited. There is a section of code that creates a Select box using a ListBoxFor based on a search term that's entered by the user:
#Html.ListBoxFor(m => m.SelectedItem,
Lookup.Models.myService.Search(Model.SearchTerm,
null == Model.SelectedCity ? 1 :
Int32.Parse(Model.SelectedCity))
The signature for Search() is:
public static List<SelectListItem> Search(string term, string city)
Instead of displaying a Select box, I want to output an HTML table instead with the data. I'm not even sure how to go about doing this or really what info to give you all in order to help me :)
The ListBoxFor helper displays <select> elements with multiple="multiple" attribute allowing multiple selections. If you want something else you should not use this helper. So you said that you wanted an HTML table.
Now, there's something very wrong with the code you have shown. You are calling Lookup.Models.myService.Search inside a view. Views are not supposed to pull data from some places. They are supposed to only display data that is being passed to them under the form of view models by a controller action. So this call should not be done in the view. It should be done beforehand and the result stored as a property on your view model:
public IEnumerable<SelectListItem> Items { get; set; }
Anyway. The first possibility is to write the markup yourself:
<table>
<thead>
<tr>
<th>Value</th>
<th>Text</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Items)
{
<tr>
<td>#item.Value</td>
<td>#item.Text</td>
</tr>
}
</tbody>
</table>
Of course writing this code over and over again could become cumbersome. So you could externalize it in a DisplayTemplate. For example you could put it inside a ~/Views/Shared/DisplayTemplates/MyTableTemplate.cshtml and then when you needed to render it in a view you could use:
#Html.DisplayFor(x => x.Items, "MyTableTemplate")
I'm working in MVC3 with Entity Framework. I've got an entity called Product that has two properties I'd like to validate when a user adds a new record. To do this, I've created a buddy class, as so:
using System;
using System.ComponentModel.DataAnnotations;
namespace Rpm.Data.Partials
{
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
}
}
The metadata class is as so:
using System;
using System.ComponentModel.DataAnnotations;
namespace Rpm.Data.Partials
{
public class ProductMetadata
{
[Required]
public string ProductName { get; set; }
[Range(200, 1000, ErrorMessage = "You must select a valid Account Type")]
public int AccountTypeId { get; set; }
}
}
The view that allows users to add a new record is like this:
#model Rpm.Data.Product
#{
ViewBag.Title = "Product"
}
<script type="text/javascript">
$(document).ready(function() {
//There should be no selection in the drop-down box when the form is first displayed.
document.getElementsByTagName("select")[0].selectedIndex = -1;
}
function formSubmit() {
var form = $("form");
if (form.valid()) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
document.getElementById("frmNewProduct").submit();
return true;
}
else {
return false;
}
}
</script>
<h2>Add New Product</h2>
#using (Html.BeginForm("Create", "Product", new { id = new Product() }, FormMethod.Post, new { id = "frmNewProduct" }))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td>
Product Name
</td>
<td>
#Html.TextBoxFor(m => new Product().ProductName)
#Html.ValidationMessageFor(m => new Product().AccountTypeId)
</td>
</tr>
<tr>
<td>
Account Type
</td>
<td>
#Html.DropDownListFor(m => new Product().AccountTypeId, new SelectList(Lookup.Instance.AccountTypes, "AccountTypeId", "AccountTypeName"))
#Html.ValidationMessageFor(m => new Product().AccountTypeId)
</td>
</tr>
<tr>
<td />
<td>
<input type="image" src="#Url.Content("~/Content/images/savebutton.png")" onclick="return formSubmit()" />
</td>
</tr>
</table>
}
(Of course, the above is quite simplified just to avoid overloading the post with code that's not really relevant.)
The problem is that, when the user clicks the Save button, the validation for the ProductName fires just fine and displays the validation message if the field is blank; however, the message for AccountTypeId is never displayed, even if the drop-down is left without a selection (selectedIndex == -1). I know the RangeAttribute on AccountTypeId is being picked up, because when EF tries to save changes to the entities, it throws a DbEntityValidationException, and the text of the ErrorMessage is the custom error message I specified in the metadata. I just can't seem to get it to display on the page and cause the form to fail validation, preventing the user from saving.
Any suggestions as to what I'm doing wrong would be most appreciated!
TIA,
Jeff
When you do this:
#Html.TextBoxFor(m => new Product().ProductName)
#Html.ValidationMessageFor(m => new Product().AccountTypeId)
You're create two entirely different Product() instances, and you create additional Product instances for each property. this might work, since MVC is just using the lambda to create a layout format, but it's in general not very efficient and wastes memory.
Your model type is already product. You should just be using m => m.ProductName
This might be confusing the validation system. I'd just do as I suggest and see if the problem continues.
You also don't need the javascript to set the dropdownlist type. Just do this:
#Html.DropDownListFor(m => new Product().AccountTypeId,
new SelectList(Lookup.Instance.AccountTypes,
"AccountTypeId", "AccountTypeName"), "Select")
And make sure AccountTypeId is nullable int, and you put a [Required] attribute on it. The validator will make sure there's a value.
I'm also not sure why you're using the formSubmit code. image inputs are already submit types, so they submit the form when you click on them. You don't appear to actually be doing anything other than submitting the form again.
I want to be able to update a model and all its collections of child objects in the same view. I have been referred to these examples: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ .
For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. In the view, the simple properties of the Consultant object is no problem, but the collection I cannot get a textbox to show up for. I tried following the examples in the links above, but it doesn't work. The problem is, in those examples the model is just a list (not an object with a child list property). And also, the model again is an EF model. And for some reason that doesn't seem to work as in those examples.
Just to make it simple, I tried to do something along the lines of Phil Haacks example, and just get the View to show the textbox:
#for (int i = 0; i < Model.WorkExperiences.Count; i++)
{
Html.TextBoxFor(m => m.WorkExperiences[i].Name);
}
I tried to create a new WorkExperience object in the controller for the ViewModel:
public ActionResult Create(int id)
{
Consultant consultant = _repository.GetConsultant(id);
DetailsViewModel vm = new DetailsViewModel();
vm.WorkExperiences = consultant.WorkExperiences.ToList();
vm.WorkExperiences.Add(new WorkExperience());
return View(vm);
}
But the View doesn't show any empty textbox for the WorkExperience Name property. If on the other hand I create a separate View just for adding a new WorkExperience object, passing a new empty WorkExperience object as the model, this works fine:
#Html.EditorFor(model => model.Name)
That gives me an empty textbox, and I can save the new object. But why can't I do this in the same view as the Consultant object, with collections according to the examples in the links above?
BTW, this is sort of a follow-up question to an earlier one, that pointed me to the above links, but I never got to a final solution for it. See that question if more info is needed: Create Views for object properties in model in MVC 3 application?
UPDATE:
According to answers and comments below, here's an update with the View and an EditorTemplate:
The View:
#model Consultants.ViewModels.DetailsViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Add work experience", "CreateWorkExperience", new { id = ViewBag.Consultant.Id })
</p>
<table>
<tr>
<th></th>
<th>
Name
</th>
</tr>
#foreach (var item in Model.WorkExperiences) {
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
<td>
#item.Name
</td>
</tr>
}
</table>
#for (int i = 0; i < Model. WorkExperiences.Count; i++)
{
Html.EditorFor(m => m. WorkExperiences[i]);
}
(Please note that all this is not really how I'll design it in the end, all I am after right now is to get the WorkExperience object to show up as an empty textbox to fill out, and to be able to add and delete such textboxes as in Phil Haack's and Steven Sanderson's examples.)
The EditorTemplate:
#model Consultants.Models.WorkExperience
#Html.TextBoxFor(m => m.Name);
This stuff with the EditorTemplate works fine in Phil Haack's sample project, which I downloaded to try, but here, with the EF model or whatever the problem is, I don't get any textbox at all. The table in the view is just there as a test, because in the table I do get the rows for WorkExperiences, whether I add an empty WorkExperience object or fill out its properties doesn't matter, the rows show up for each object. But again, no textbox...
For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model.
That's the first thing you should improve: introduce view models and don't use your domain models into the view.
This being said let's move on to the templates. So you can completely eliminate the need to write loops in your views.
So here's how your view might look like:
#model Consultants.ViewModels.DetailsViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Add work experience", "CreateWorkExperience", new { id = ViewBag.Consultant.Id })
</p>
<table>
<tr>
<th></th>
<th>
Name
</th>
</tr>
#Html.DisplayFor(x => x.WorkExperiences)
</table>
#Html.EditorFor(x.WorkExperiences)
So as you can we are using a display template and an editor template. Let's define them now.
Display template (~/Views/Shared/DisplayTemplates/WorkExperience.cshtml):
#model AppName.Models.WorkExperience
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
#Html.ActionLink("Details", "Details", new { id = Model.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = Model.Id })
</td>
<td>
#Model.Name
</td>
</tr>
Editor template (~/Views/Shared/EditorTemplates/WorkExperience.cshtml):
#model AppName.Models.WorkExperience
#Html.TextBoxFor(x => x.SomePropertyOfTheWorkExperienceModelYouWantToEdit)
...
What is important here is the naming convention. The name of the template should be the name of the type of the item in the collection. So for example if in your view model you have a property
public IEnumerable<Foo> { get; set; }
the corresponding template should be called Foo.cshtml and should be located in ~/Views/Shared/DisplayTemplates or ~/Views/Shared/EditorTemplates depending on its role.
So as you can see we have gotten rid of the nasty loops. Now not only that the views look clean, but you get correct names for the input fields so that you can bind the values back in the post action.
The easiest way to do this is probably to create a WorkExperienceList class that inherits List<WorkExperience> (or List<string>, if that's what they are) and then create a custom template for your WorkExperienceList. That way, you'd simplify your view code to #Html.EditorFor(Model), and ASP.NET MVC would take care of the rest for you.