How to update hierarchical ViewModel? - asp.net-mvc-3

I am stuck with this problem.
I have a model AssessmentModel defined like this:
public class AssessmentModel
{
public Respondent Respondent { get; set; }
public List<CompetencyModel> Competencies { get; set; }
}
public class CompetencyModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<ResultModel> Results { get; set; }
}
public class ResultModel
{
public int Id { get; set; }
public int Score { get; set; }
}
All I need is to set value to the Score property of ResultModel.
Score is the only editable property here.
And I have just 1 View only, this view has a #model List, it displays a list of CompetencyModel items with Edit button for each one.
When I click the Edit button, the Id of CompetencyModel is passed to the same View, and the View draws an Edit form for ResultModel items that belong to the selected CompetencyModel.
However the form for ResultModel items exists on the same View, and the model of the View is still #model List.
How can I get to the Score property by using bindable Html.EditorFor(m=>m.Score) helper for each ResultModel item?
The View is defined like this:
#model List<CompetencyModel>
#foreach(var comp in Model)
{
<p>#comp.Name</p>
Edit
}
In the controller I set ViewBag.CurrentId = comp.Id, and at the bottom of the View:
if(ViewBag.CurrentId != null) //draw a form for ResultModel items
{
// What should I do now?
// how cant I use Html.EditorFor(m=>...) if the Model is still List<CompetencyModel>
}
I need to get to a single ResultModel entity to set a value to a Score property.
Thank you.

You should be able to get this done using Linq. Consider having the following code segment in the your last if statement
var result = Model.Results.FirstOrDefault(r => r.Id == ViewBag.CurrentId);
I dont have a IDE with me, so watchout for syntext errors

Related

Drop down is not maintaining its State and showing only selected value

I want to select year from my drop down list and that year will be passed to my procedure in the where clause and will get the results. It works fine but on the view the selected value is only visible.
Example If I select 2015 from my drop down list which has 2015 and 2016 values then on the view only 2015 is visible on the drop down.
Records are perfectly fetched.
Model
public class Data
{
[Key]
public string DataName { get; set; }
public int Year { get; set; }
}
Controller
public ActionResult Test()
{
VMNews objnews = new VMNews();
if (Request["ddlYear"] != null)
{
string selectedValue = Request["ddlYear"];
objnews.DataName = db.Database.SqlQuery<Data>("usp_year #Year",new SqlParameter("#Year",selectedValue)).ToList();
}
Response.Write("Nothing Selected");
return View("Index",objnews);
}
View
using (Html.BeginForm("Test","Home"))
{
#Html.DropDownList("ddlYear", new SelectList(Model.MovieName, "Year", "Year"), "ALL")
<button type="submit">Button</button>
}
}
Problem is there at the view level only, I had used the HTTPPost option on the controller and on the view ForMethod.POST but it didnt worked.
If I get this straight, u want to add a listItem with more than 1 value?
In this case you should concat data into a sigle string value
(remove public int Year { get; set; }/ add public string Year { get; set; } ) and then split it on the POST (ActionResult Test) and use them on your procedure.

How to keep a collection of items for dropdown list in MVC model?

to keep things simple, I have a model Survey with the following properties:
class SurveyItem {
public string Question { get; set; }
public string SelectedAnswerCode { get; set; }
public List<Answer> Answers { get; set; }
}
where Answer is like:
class Answer {
public int AnswerCode { get; set; }
public string AnswerText { get; set; }
}
Answers is used to build a dropdown listbox of possible answers for (a user selects one)
In my View I use a Model of IEnumerable
where for each question I have a list of answers to choose from.
I prefill this collection and pass to my View. When I click submit, it goes back to the controller for validation. If the model is not valid, I pass it to the same View for a user to fix his answers, like usual.
Question - Answers collection used for dropdown list is not preserved in the model when I submit. I use HiddenFor, EditorFor and DropDownListFor for single value properties, but, how do I keep a collection of possible answers in the Model?
P.S>
Thanks.
P.S. I am using single line code #Html.DropDownListFor to render the dropdown in my EditorTemplate:
#Html.DropDownListFor(model => model.SelectedAnswerCode,
new SelectList(Model.Answers, "AnswerCode", "AnswerText", 0))
You'll need to add virtual to the Answers declaration.
class SurveyItem {
public string Question { get; set; }
public string SelectedAnswerCode { get; set; }
public virtual List<Answer> Answers { get; set; }
}
This seems to do the trick: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
Basically in your view do something like this:
#for(int i = 0; i < Model.Answers.Count; i++)
{
#Html.Hidden(string.Format("Answers[{0}].AnswerCode", i), Model.Answers[i].AnswerCode)
#Html.Hidden(string.Format("Answers[{0}].AnswerText", i), Model.Answers[i].AnswerText)
#Html.RadioButton("SelectedAnswerCode", Model.Answers[i].AnswerCode)
#Model.Answers[i].AnswerText
}
EDIT:
Alternatively, you can create your own HtmlHelper extension. For example:
public static class CustomHtmlHelperExtensions
{
public static MvcHtmlString HiddenForSurveyAnswers(this HtmlHelper htmlHelper, IEnumerable<Models.Answer> answers)
{
var html = new StringBuilder();
int index = 0;
foreach (var answer in answers)
{
html.AppendLine(htmlHelper.Hidden(string.Format("Answers[{0}].AnswerCode", index), answer.AnswerCode).ToString());
html.AppendLine(htmlHelper.Hidden(string.Format("Answers[{0}].AnswerText", index), answer.AnswerText).ToString());
index++;
}
return MvcHtmlString.Create(html.ToString());
}
}
Then add an #using YourMvcApplicationNamespace to the top of the view and then use the extension like:
#Html.HiddenForSurveyAnswers(Model.Answers)
With MVC, you can write an Editor Template to preserve the Model.Answers as well :)
Save a view named Answer.chtml in \Views\Shared\EditorTemplates.
Add the following code:
#model Answer
#Html.HiddenFor(item => item.AnswerCode)
#Html.HiddenFor(item => item.AnswerText)
Then in you original view, add it:
#Html.EditorFor(model => model.Answers)
#Html.DropDownListFor(model => model.SelectedAnswerCode, new SelectList(Model.Answers, "AnswerCode", "AnswerText", 0))
In this manner you don't have to worry about writing foreach statements or worry about their ids.
Hope it helps.

implementing dropdownlist in asp.net mvc 3

I am teaching myself asp .net mvc3. I have researched a lot but the more I read the more confused I become. I want to create a page where users can register their property for sale or rent.
I have created a database which looks like this:
public class Property
{
public int PropertyId { get; set; }
public int PropertyType { get; set; }
ยทยทยท
public int Furnished { get; set; }
...
}
Now, I want dropdownlistfor = PropertyType and Furnished.
Property type would be
1 Flat
2 House
3 Detached House
...
Furnished would be:
1 Furnished
2 UnFurnished
3 PartFurnished
...
Now, I am really not sure where to keep this information in my code. Should I have 2 tables in my database which store this lookup? Or should I have 1 table which has all lookups? Or should I just keep this information in the model?
How will the model bind to PropertyType and Furnished in the Property entity?
Thanks!
By storing property types and furnished types in the database, you could enforce data integrity with a foreign key, rather than just storing an integer id, so I would definitely recommend this.
It also means it is future proofed for if you want to add new types. I know the values don't change often/will never change but if you wanted to add bungalow/maisonette in the future you don't have to rebuild and deploy your project, you can simply add a new row in the database.
In terms of how this would work, I'd recommend using a ViewModel that gets passed to the view, rather than passing the database model directly. That way you separate your database model from the view, and the view only sees what it needs to. It also means your drop down lists etc are strongly typed and are directly in your view model rather than just thrown into the ViewBag. Your view model could look like:
public class PropertyViewModel
{
public int PropertyId { get; set; }
public int PropertyType { get; set; }
public IEnumerable<SelectListItem> PropertyTypes { get; set; }
public int Furnished { get; set; }
public IEnumerable<SelectListItem> FurnishedTypes { get; set; }
}
So then your controller action would look like:
public class PropertiesController : Controller
{
[HttpGet]
public ViewResult Edit(int id)
{
Property property = db.Properties.Single(p => p.Id == id);
PropertyViewModel viewModel = new PropertyViewModel
{
PropertyId = property.Id,
PropertyType = property.PropertyType,
PropertyTypes = from p in db.PropertyTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.PropertyTypeId.ToString()
}
Furnished = property.Furnished,
FurnishedTypes = from p in db.FurnishedTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.FurnishedTypeId.ToString()
}
};
return View();
}
[HttpGet]
public ViewResult Edit(int id, PropertyViewModel propertyViewModel)
{
if(ModelState.IsValid)
{
// TODO: Store stuff in the database here
}
// TODO: Repopulate the view model drop lists here e.g.:
propertyViewModel.FurnishedTypes = from p in db.FurnishedTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.FurnishedTypeId.ToString()
};
return View(propertyViewModel);
}
}
And your view would have things like:
#Html.LabelFor(m => m.PropertyType)
#Html.DropDownListFor(m => m.PropertyType, Model.PropertyTypes)
I usually handle this sort of situation by using an enumeration in code:
public enum PropertyType {
Flat = 1,
House = 2,
Detached House = 3
}
Then in your view:
<select>
#foreach(var val in Enum.GetNames(typeof(PropertyType)){
<option>val</option>
}
</select>
You can set the id of the option equal to the value of each item in the enum, and pass it to the controller.
EDIT: To directly answer your questions:
You can store them as lookups in the db, but for small unlikely to change things, I usually just use an enum, and save a round trip.
Also look at this approach, as it looks better than mine:
Converting HTML.EditorFor into a drop down (html.dropdownfor?)

select the value to populate html.dropdownlist

I have two classes as follows
public class ODCTE_Major
{
public int ODCTE_MajorId { get; set; }
public string OfficialMajorName { get; set; }
public string MajorCode { get; set; }
... More unrelated code ....
}
AND
public class CareerMajor
{
...lots of unrealted code to this question left out
public int ODCTE_MajorId { get; set; }
public virtual ODCTE_Major ODCTE_Major { get; set; }
}
I added a controller with CRUD methods and in the create.cshtml there is this line
<div class="editor-field">
#Html.DropDownList("ODCTE_MajorId", String.Empty)
#Html.ValidationMessageFor(model => model.ODCTE_MajorId)
</div>
The select list populates it with the OfficialMajorName from ODCTE_Major. I need the select list to populate with the MajorCode or a value that looks like MajorCode - OfficialMajorName.
Could someone provide assistance for how this is done, please?
Thanks.
Add this to ODCTE_Major:
public string MajorDisplayName
{
get { return string.Format("{0} - {1}", MajorCode, OfficialMajorName); }
}
This is just a read only property used to create the display text in the format you want the menu to use.
Then in CareerMajor, add:
public IEnumerable<ODCTE_Major> Majors{ set; get; } // Thank you Shyju!
This will give you a place in your view model to pass the list of Majors you want in your menu to the view.
Then in your action method when you're creating a CareerMajor view model to send to the view, populate the new IEnumberable with the ODCTE_Major entities you'd like displayed in your menu.
On the view page:
#Html.DropDownListFor(m => m.ODCTE_MajorId, new SelectList(Model.Majors, "ODCTE_MajorId", "MajorDisplayName", Model.ODCTE_MajorId), "Select One")
This creates a SelectList to populate the drop down with. The SelectList constructor is saying use ODCTE_MajorId as the value for a SelectListItem in the menu, and to use MajorDisplayName as the text to actually display in the menu. It sets the selected value, if there is one, and adds a null item with the text "Select One" to the top of the menu. Feel free to take that final argument out if you don't want the null text.
Have your ViewModel hold a Collection property to represent all available Majors (for poulating the Dropdown)
public class CareerMajor
{
//other proiperties
public int ODCTE_MajorId { get; set; }
public IEnumerable<ODCTE_Major> Majors{ set; get; }
}
And in your GET Action, fill it and send it to your strongly typed view
pubilc ACtionResult Create()
{
var viewModel=new CareerMajor();
viewModel.Majors=db.GetllAllMajors(); // getting a list of ODCTE_Major objects
return View(viewModel);
}
and in the View, use the DropDownListFor HTML Helper method.
#model CareerMajor
#Html.BeginForm())
{
#Html.DropDownListFor(m=>m.ODCTE_MajorId,
new SelectList(Model.Majors,"ODCTE_MajorId ","MajorCode"),"select one..")
//other elements
}
In your controller action:
ViewBag.ODCTE_MajorId = new SelectList(availableMajors, "ODCTE_MajorId", "MajorCode");
*second and third parameters are the names of the value and text fields respectively
Then in your view:
#Html.DropDownList("ODCTE_MajorId", String.Empty)
where availableMajors is an IEnumerable that contains the majors you want to list.

Two render bodies in layout page?

I understand that only 1 RenderBody can exist in the MVC3 layout page however I want to attempt to create another. Maybe I'm looking at it the wrong way... Ideally I want to add a testimonial section that pulls in from the DB and display 1 testimonial at a time and a different 1 for each page refresh or new page. What is the best way to go about this?
Controller
CategoryDBContext db = new CategoryDBContext();
public ActionResult Testimonial(int id)
{
TestimonialModel model = db.Testimonials.Find(id);
return View(model);
}
Model
public class TestimonialModel
{
public int ID { get; set; }
public int CategoryID { get; set; }
public string Data { get; set; }
}
public class CategoryDBContext : DbContext
{
public DbSet<TestimonialModel> Testimonials { get; set; }
}
The View is in a folder called CategoryData.
You need to be use:
Layout:
#RenderSection("Testimonial", false) #*false means that this section is not required*#
and in you View
#section Testimonial{
}
I would use #Html.Action()
Here is a great blog post about using them: https://www.c-sharpcorner.com/article/html-action-and-html-renderaction-in-Asp-Net-mvc/
This would allow you to have a TestimonialController that can take in values, query for data and return a partial view.

Resources