How to Fill ListBox - asp.net-mvc

I think my question is basic but I can't find the way to do this issue in Asp.Net MVC 3.
I have a Model with the Controller called "Concepto". I want to see into the Create view, a ListBox with all the data from Concepto model.
The Index view show the complete data from the model, so the database connection and EF process are correct.

Hi you should create a strongly typed view using the model. Once you have the model in the context of the view, you can use the MVC helpers to render the data. For example if you have multi line postal address data stored in a property PostalAddress, you can use
#Html.TextAreaFor(m => m. PostalAddress)
You can further customise the text area by providing col and row information as the second parameter
#Html.TextAreaFor(m => m. PostalAddress, new {#cols=”50”, #rows=”20”})
Hope this helps

You can't display all the data in a ListBox. However, you can have a field as List itme's display text and another as its value (like ID) using #Html.ListBoxFor() method which expects a name of a field and a collection of item eg. #Html.ListBoxFor(model => m.someId, Model.CollectionData);
Thanks,

Related

How to show the value of model in Kendo Custom Editor Template?

I'm using a scheduler of Kendo UI for MVC. I created a Custom Editor Template. It works fine. When click the schedule, it pops a windows and show the info.
I added some properties in the model, the value passed to the editor template. Now, the question is:
How can I show the added properties (just as value, and I do not want to change it) in the editor template popup?
I found that if I use a textbox:
#(Html.TextBoxFor(model => model.Role, new { #class = "k-textbox" }))
It shows a textbox and shows the correct value of Role. However, if I use
<div>#(Model.Role)</div>
It shows blank, just as the value is NULL.
I actually want to show several added properties as a sentence, i.e. I added Role and UserName and I ant to show something like:
UserNameValue has Role of RoleValue
Anyone knows how to do it?
I use this as sample in the code:
http://www.telerik.com/support/code-library/custom-editor
Thanks
Your solution is to put this line because the editor template is binded by mvvm
<div data-bind="text: Role"></div>
Docs
In the code: model => model.Role model is just an alias, not an actual object. You could replace it with m => m.Role and it would function the same.
When you write #Model in your view you are using the object of ContractViewModel which is passed from Controller action, if it is not passed from View it can be null and accessing any property of Model can throw Null Reference Exception and writing Model.Contractors you basically mean ContractViewModel.Contractors
See this post: mvc uppercase Model vs lowercase model

Adding / Removing MVC typed partial view to form on mouse click

first question on stack so please be gentle ;). I have a long MVC form that requires the user to be able to click an 'Add Person' button , which would then create a copy of an 'Add Person' partial view , which is then filled in with the Person details. On form submit, the controller would then need to contain the details of each new added person stored as a Person object in the Person[] array I have in my View Model. so for example:
User clicks 'Add Person' button 3 times
3x ' Add Person' partial views are displayed on screen, one after the other
User fills in the 3 listed forms
User submits form
Model submitted to controller contains an array of 3 Person objects, populated with the values the user has entered.
I've got the EditorFor working when displaying a list of template forms for an already populated Array of Person objects, but not sure how I would go about actually inserting a new 'Person' into the model via mouse click. Each new person will need to be given an ID of Guid type.
Sorry if my question is vague.I'm trying not to be. I cant provide sample code for my exact solution as this is for a government project but can whip up an similar example if required. Thank you for your time
This should give you a general idea of how to do it
var partialView = '#Html.Raw(#Html.Partial("Person", new ViewModel()).ToString().Replace("\r\n", String.Empty).Replace("\n", String.Empty).Replace("\r", String.Empty))';
partialView = partialView.replace('id="1"', 'id=ListName_{0}'.format(newId));
$("#persons").append(partialView);
Firstly I create a variable containing the partial view as a string, next we need to change the ids and the rest of the properties so they follow the convention used for lists when data binding in MVC.
It follows the following convention
<input type="text" name="stocks[0].Key" value="MSFT" />
<input type="text" name="stocks[1].Key" value="AAPL" />
See the following for a description
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
Once all ids are correctly created you can post the form as per usual.
You're not going to be able to add a person to the view model from client side code. The view model doesn't exist client side, only server side.
My suggestion is to make sure the partial views are all in the form being submitted and have an array of Person objects as a parameter in the controller action you're posting to. You'll need to make sure you use the correct convention for each name on each input field of each partial view.
So for example the partial view each input field would need to be named like this Person[index].Field. Where index is an integer and Field is the appropriate property from the Person model that this particular input tag represents.

How do you render 2 models on a view in asp.net mvc 4?

I have a page that will have some textboxes that will save to a table called Values, let's say. The textboxes that I display will populate the selection from a dropdownlist. This dropdownlist will get its values from another table in the database called DropDownListValues. I am assuming that my controller would be built on the Values model but I guess I am a little bit confused as to how I will give the values to the dropdownlist. Do I store it in a ViewBag or render a partial view? Just trying to find the best approach here as I am a little new to asp.net mvc.
Yes, you store them in viewBag
ViewBag.CompanyTypes = _Repository.GetCompanyTypes().
Select(p => new SelectListItem { Text = p.CompanyType1, Value = p.CompanyTypeID.ToString() });
and use it like that:
#Html.DropDownListFor(model=> model.CompanyTypeID, (IEnumerable<SelectListItem>)ViewBag.CompanyTypes )
I think that you can use both of them and question is store in ViewBag or render partial view? answer: yes, you can use both of them when you need. And you can prepare specific extensions for example for cities, offices, few popular users etc.
Use a ViewModel. This was in a comment but I cannot accept that as an answer so I decided to post an answer

How to access model property in Razor view of IEnumerable Type?

How to access Model property(Like #Html.EditorFor(x=>Model.Name)) in Razor view of IEnumerable Type without using Loops??I.e If a view is strongly typed to some Model holding Model as a LIST.Eg.
#model IEnumerable<EFTest2.DAL.package_master>
Then is it possible to Display TestBoxFor or EditorFor (to create new Model) Html helper without using foreach Loop.???
When some model property is of type IEnumerable<SomeType> you would normally define an editor/display template (~/Views/Shared/EditorTemplates/SomeType.cshtml or ~/Views/Shared/DisplayTemplates/SomeType.cshtml). This template will be automatically rendered for each element of the collection so that you don't need to write loops:
#Html.EditorFor(x => x.SomeCollection)
and inside the template you will be able to access individual properties:
#model SomeType
#Html.EditorFor(x => x.Name)
...
Now, if you absolutely need to directly access some element inside a view which is strongly typed to IEnumerable<SomeType> you would better use some other collection type such as IList<SomeType> or SomeType[] as view model which will give you direct access to elements by index and you will be able to do this for example to access the 6th element of the collection:
#model IList<SomeType>
#Html.EditorFor(x => x[5].Name)
So basically you are mentioning of type List etc.
If you want to add values to the list accepting input from user from form fields and then add to the existing list in model. the easiest but not so elegant way would be
suppose you have class "Person" and then List in your model. first create an instance of person that will have empty person instance , add it to list and then bind this last list item to your edit for.
#{
Person contact = new Person(); //Empty person instance
PersonList.Add(contact);
}
later on bind this to your induvidual fields
#Html.TextBoxFor(m => m.PersonList[PersonList.Count - 1].PrimaryContacts.FirstName)
This works good for Validation on model properties as-well and also after every form submit, for next inclusion you just add the new person. but take care to write the remove peice of code if form is cancelled.

Using multiple partial views in MVC3 razor forms

I have an insurance entry form that has contact information for two people. I have created a Razor partial view for the contact entry and put it in the form twice. The 'master' view model (VmApplicationForm) contains two instances of a subsidiary view model (VmPolicyHolder) corresponding to the two contacts as well as some properties common to both contacts. I am calling #Html.RenderPartial("_CreateOrEdit", Model.contactInfo1) and #Html.RenderPartial("_CreateOrEdit", Model.contactInfo2) in the page. With this arrangement (no surprises) the rendered code has duplicate IDs for the form input elements.
Is there any way of getting RenderPartial to prefix the IDs and Name attributes? I couldn't see this in the documentation, but perhaps I've missed something.
Sorry, I don't have time yet to give you the example code, but i'll give you the idea. You should first create EditorTemplate for that probably called ContactInfo class. And then, in the base class(Holding that two contacts) edit view, you should write
#Html.EditorFor(model => model.contactInfo1)
#Html.EditorFor(model => model.contactInfo2)
This way, it will render that EditorTemplate and generate correct ids and names to inputs within it.
What you are doing is trying to post a collection of items in a form- this can indeed be done in MVC (as well as in any web page/application that uses a FORM tag), however it requires some special handling to avoid id collisions and to correctly format the post data. Steve Sanderson has a great post on how to accomplish this:
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
Essentially its a wrapper to append unique guids to element ids (in your case for each contactInfo), and create the proper array format in the tags. eg <input name="ContactInfo[f2cc4d6b-fc32-45e9-9d3d-fce54c3fede3].FirstName">
if your model is something like ContactInfo, you will end up posting like
[HttpPost]
public ActionResult Index(IEnumerable<ContactInfo> contacts)
{
// To do: do whatever you want with the data
}

Resources