inside single view create form as well as display data - asp.net

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)
{
....
}

Related

Populate drop down from database with Angular in .net

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

Delete Field Spring MVC

I am using SimpleFormController with a result page looking like this:
<tr>
<td>Name: </td>
<td>${product.name}</td>
</tr>
<tr>
<td>Text: </td>
<td>${product.text}</td>
</tr>
A user can enter a name and some text. I'm trying to implement a delete functionality for each entry (there should be a link next to each entry). I'm having trouble with understanding, if it can be done in the same Controller as for the input or not (am new to Spring) and how. The onSubmit method helps to display data that was added, do I need to implement an extra delete method? If yes, how can I "map" it to my delete link in my jsp?
I suppose you are not wanting to put a delete link even when the user is just entering the name!
Delete links should normally appear when you are displaying data, not creating them.
Here is how you can create a delete link according to associated ids.
<tr>
<td>Name: </td>
<td>${product.name}</td>
<td>delete</td>
</tr>
and this should be in your controller:
#Controller
public class ProductController{
#RequestMapping("/delete/{id}")
public String deleteProduct(#PathVariable("id")Integer id) {
// get product by id
// delete that product
// save database
// or do as you wish
return "redirect:/index";
}
}
Hope that helps :)

Adding invoice lines with ASP.NET MVC

I'm creating ASP.NET applications with MVC 4 Technology, and I want to allow the end-user to enter line items onto an invoice. I want the user to have the ability to add as many line items as they wish to the invoice, and then when they are finished to be able to click the Save button on the form which would then write the invoice and all line item data to the database. Can somebody help guide me how to handle this?
This is the way I decided to do it after several other ideas failed me. It may sounds strange, but please bear with me. I used the MVC Index View as a basis.
Before the user even sees the Invoice, I add a new Invoice to the database so that I have an Invoice ID. I then display the Invoice Index View. But instead of the table showing #foreach (var item in Model) I changed it to #foreach (var item in Model.LineItems). Its blank now, but after I add some LineItsms I will be displaying a list of LineItems - which is exactly what an invoice is.
But we want to be able to add on our Invoice Index View as well. So at the top of the Index View, in the part where you can code, create a new LineItem and save its LineItem.invoiceID as the Model.ID. Then before you display the table of LineItems add a partial View - Create LineItem.
Now you have a list of Invoice Lines on a page where you can add new ones.
Here's some code from the Index View of LineItem:
#model MyAppName.Models.Invoice
#{
ViewBag.Title = "Index";
MyAppName.Models.LineItem line = new LineItem();
line.invoiceID = Model.ID;
}
<h2>Invoice</h2>
#Html.Partial("Create", line)
<table>
<tr>
<th>
#Html.DisplayName("Amount")
</th>
<th>
#Html.DisplayName("Description")
</th>
<th></th>
</tr>
#foreach (var item in Model.LineItems)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Amount)
</td>
#Html.DisplayFor(modelItem => item.Description
</td>
<td>
#Html.ActionLink("Delete", "DeleteConfirmed", new { id = item.invoiceID })
</td>
</tr>
}
<tr>
<th>Total</th>
<th>R #Model.LineItems.Sum(amt => amt.Amount)</th>
<th></th>
<th></th>
</tr>
</table>
And here is what it looks like (except that mine was not an Invoice):
You want something like this. But it will be much more complex for your case. Use jquery to simplify your work.
$('#add_item').click(function() {
$('#invoice_listing tbody')
.append(
"<tr><td>" + $('#item').val() + "</td>" +
"<td>" + $('#amount').val() + "</td></tr>"
)
});
On every line item being added, the [Add Item] button will fire an event to do a ajax post of the line item data to the MVC controller. The controller will then do business logic and store the line item data into the database. Once the transaction is successful, the controller should return a "success" flag to the client browser. Use JSON for that will help. Your javascript should recognize the "success" flag, and add the item to the item listing.
Then finally, user will pressed on [Save] button, which complete the whole invoice data entry. You should then marked the invoice as successfully entered.
Try not to let user keep on adding the line item without being saved. They will be angry when saving failed after adding lines of item.
Have a popup where your users can search for the line items and add them. When selected capture the ItemId and use it to build a row, probably a tr or a div. So then you will have a tr or div for each line item that contains the Id of the line item and then one or two textboxes. Say a textbox for the quantity and another for the price. Then either do an ajax post where you iterate all the divs and put that info as a json data and post it to your controller method. Or format each div where your binding can collect them and be submitted when you do a postback - via your submit button. That should get you starting.

How to output HTML Table instead of a Select box (generated with ListBoxFor) in ASP.NET?

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")

Collection of complex child objects in Asp.Net MVC 3 application?

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.

Resources