Html - Get value from database - c#

So I want to get the titlefor that image in the database. How do I do it? It's showing Describe your post... for all images instead of the actual title of the image in the database
https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png
View:
#foreach (var image in Model.Images)
{
<h2>#Html.LabelFor(m => m.title)</h2>
<div class="row">
<div class="col-md-8 portfolio-item">
<img class="portrait" src="#Url.Content(image)" alt="Hejsan" />
</div>
</div>
}
Model
[Table("MemeImages")]
public class UploadFileModel
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string location { get; set; }
public IEnumerable<string> Images { get; set; }
public int contentLength { get; set; }
public string contentType { get; set; }
public string userID { get; set; }
[Required]
[Display(Name = "Describe your post...")]
public string title { get; set; }
public void SavetoDatabase(UploadFileModel file)
{
ApplicationDbContext db = new ApplicationDbContext();
db.uploadedFiles.Add(file);
db.SaveChanges();
}
}

Instead of label use directly <h2>m => m.title</h2>

Remove the display attribute.
[Required]
public string title { get; set; }
Also, LabelFor() is not the right thing. You may want to use Display/DisplayFor() to render the value.

Related

this error occurs when i press on the create button in create post form

An unhandled exception occurred while processing the request sql exception asp.net core .
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_AspNetUsers_AuthorId". The conflict occurred in database "LostKidsDb", table "dbo.AspNetUsers", column 'Id'.
Here is the Post Model
[Key]
public int PostId { get; set; }
[Required]
public string Title { get; set; }
public string Descripition { get; set; }
public string Image { get; set; }
public string Address{ get; set; }
[Display(Name ="Category")]
public int CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public Category Category{ get; set; }
[Display(Name = "Sub-Category")]
public int SubCategoryId { get; set; }
[ForeignKey("SubCategoryId")]
public SubCategory SubCategory { get; set; }
[Display(Name = "Author-Id")]
[Required]
public string AuthorId { get; set; }
[ForeignKey("AuthorId")]
public ApplicationUser ApplicationUser { get; set; }
[Required]
[Display(Name = "Author-Name")]
public string AuthorName { get; set; }
public enum PostStatus
{
Pending,
Approved,
Rejected
}
public PostStatus Status { get; set; }
Here is the Application user model
public class ApplicationUser:IdentityUser
{
public string Name { get; set; }
public string StreetAddress { get; set; }
public string PostalCode { get; set; }
public string Governorate { get; set; }
public string City { get; set; }
}
This is the create razor view page in user controller:
<div class="col-5">
#if (SignInManager.IsSignedIn(User))
{
{
ApplicationUser applicationUser = await UserManager.GetUserAsync(User);
<input readonly asp-for="Post.AuthorName" value=" #applicationUser.Name " class="form-control" />
}
}
<span class="text-danger" asp-validation-for="Post.AuthorName"></span>
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label hidden asp-for="Post.AuthorId" class="col-form-label"></label>
</div>
<div class="col-5">
#if (SignInManager.IsSignedIn(User))
{
{
ApplicationUser applicationUser = await UserManager.GetUserAsync(User);
<input type="hidden" asp-for="Post.AuthorId" value=" #applicationUser.Id " class="form-control" />
}
}
Here is the Create Method in Post Controller in User Area:
[HttpGet]
public IActionResult Create()
{
return View(PostVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Create")]
public async Task<IActionResult> CreatePost()
{
//if (ModelState.IsValid)
//{
//in case the user didn't upload an image while creating a post a default image will be uploaded with the post
string ImagePath = #" \Images\download.png";
//uploaded images of the created post will be saved into this static file
var files = HttpContext.Request.Form.Files;
if (files.Count > 0)
{
string webroot = webHostEnvironment.WebRootPath;
// change the name of images uploaded to avoid duplicate names so every uploaded image
// will take the name of the date of its uploading
string ImageName = DateTime.Now.ToFileTime().ToString() + Path.GetExtension(files[0].FileName);
FileStream fileStream = new FileStream(Path.Combine(webroot, "Images", ImageName), FileMode.Create);
files[0].CopyTo(fileStream);
ImagePath = #"\Images\" + ImageName;
//}
PostVM.Post.Image = ImagePath;
db.Posts.Add(PostVM.Post);
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(PostVM);
}

How to post list of model on controller?

There is 1 form on which i will ask for Academic Details for :
Graduation
Post Graduation(Masters)
Professional Qualification.
So far any user say UserId="1" 3 entries will be created in my AcademicMaster each for bachelor,Master(Post Graduation) and Professional Qualification.
My Database AcademicMaster table fields and datamodel:
Id,Qualification(GraduationCourses),Acheievement,UserId
View Model:
public class AcademicViewModel
{
public int Id { get; set; }
public virtual Graduation Graduation{ get; set; }
public virtual PostGraduation PostGraduation{ get; set; }
public virtual ProfessionalQualification ProfessionalQualification{ get; set; }
}
public class Graduation
{
public string BachelorQualification { get; set; }
public string BachelorAchievement { get; set; }
}
public class PostGraduation
{
public string MasterQualification { get; set; }
public string MasterAchievement { get; set; }
}
public class ProfessionalQualification
{
public string ProfessionalQualifications { get; set; }
}
So my View is like this:
#model AcademicViewModel
#{
IEnumerable<SelectListItem> graduationList = ViewBag.GraduationList;
IEnumerable<SelectListItem> postGraduationList = ViewBag.PostGraduationList;
}
#using (Html.BeginForm())
{
<div class="row">
Bachelors
#Html.DropDownListFor(model => model.Graduation.Qualification, graduationList)
</div>
#Html.TextAreaFor(model => model.Graduation.Achievement)
<div class="row">
MASTERS
#Html.DropDownListFor(model => model.PostGraduation.Qualification, postGraduationList)
</div>
#Html.TextAreaFor(model => model.PostGraduation.Achievement)
<div class="row">
PROFESSIONAL QUALIFITCATION
#Html.TextAreaFor(model => model.ProfessionalQualification.ProfessionalQualifications)
</div>
<input type="submit" value="Save">
}
This is my Controller:
[HttpPost]
public ActionResult MyController(AcademicViewModel model)
{
//Actions
}
So is my View Model structure appropriate and how to create 3 entries in AcademicMaster Table??
I will start by saying that having one table may not be the best choice (what happens if later you start adding additional properties which may be applicable to Graduation that are not applicable to Professional - for example YearOfGraduation - you could end up with a huge number of fields, many of which may have null values.
However, if you want one table, then at least add another field so that you can identify if the data is related to Graduation, PostGraduation or Professional. The associated data model for the AcademicMasters table would be
public class AcademicMaster
{
public int ID { get; set; }
public string Type { get; set; } // may be an enum?
public string Qualification { get; set; }
public string Achievement { get; set; }
public int UserID { get; set; }
}
Side note: It might be better to use an enum for the Type property
public enum AcademicType
{
Graduation,
PostGraduation,
Professional
}
There does not seem to be any need to your current Graduation, PostGraduation and ProfessionalQualification models and your view model should be
public class AcademicViewModel
{
public string GraduationQualification { get; set; }
public string GraduationAchievement { get; set; }
public string PostGraduationQualification { get; set; }
public string PostGraduationAchievement { get; set; }
public string ProfessionalAchievement { get; set; }
public IEnumerable<SelectListItem> GraduationList { get; set; }
public IEnumerable<SelectListItem> PostGraduationList { get; set; }
}
Side notes: Its not clear what your current ProfessionalQualifications property is - does that get assigned to the Qualification field or the Acheievement field in the database? Since your using a view model, then it should include the SelectList's rather that using ViewBag.
Then your view will be
#model AcademicViewModel
#using (Html.BeginForm())
{
<h2>Graduation</h2>
#Html.DropDownListFor(m => m.GraduationQualification, Model.GraduationList)
#Html.TextAreaFor(m => m.GraduationAchievement)
... // repeat for PostGraduation and Professional
<input type="submit" value="Save">
}
And the POST method would be
[HttpPost]
public ActionResult MyController(AcademicViewModel model) // should be named Create?
{
var userID = ....
AcademicMaster graduation = new AcademicMaster
{
Type = AcademicType.Graduation,
Qualification = model.GraduationAchievement,
Achievement = model.GraduationAchievement,
UserId = userID;
};
db.AcademicMasters.Add(graduation);
// Repeat for PostGraduation and Professional
db.SaveChanges();
// redirect?
}

How to know the max value of a Object in Razor ASP .Net

So I have in my html :
#foreach (Artist artist in Model.artist)
{
<tr>
<td>#artist.attr.rank</td>
<td>#artist.name</td>
<td><div ... aria-valuenow="#artist.playcount" aria-valuemin="0" aria-valuemax="???">#artist.playcount</div></td>
</tr>
}
Where Mode.artist is :
public List<Artist> artist { get; set; }
And a Artist is defined like that :
public class Artist
{
public string name { get; set; }
public int playcount { get; set; }
public string mbid { get; set; }
public string url { get; set; }
public string streamable { get; set; }
public List<Image> image { get; set; }
[JsonProperty("#attr")]
public Rank attr { get; set; }
}
I want that the aria-valuemax="???" to be the max value for all the artists
How do I do that ?
Thanks
You can use this:
...aria-valuemax="#Model.artist.Max(x=> x.playcount)"...
But, it would be better to declare this as variable outside of the loop:
#{ int maxPlayCount = Model.artist.Max(x=> x.playcount); }
And, then just get the value from this variable:
...aria-valuemax="#maxPlayCount"...
As you are using it in a loop, you would want to calculate the value once and use it in the loop (to avoid an O(n*n) performance). You can add a property for it in the model:
public int MaxPlayCount { get; private set; }
Then set it in the model constructor after you have set the artist property:
MaxPlayCount = artist.Max(a => a.playcount);
In the markup get the value from the model:
... aria-valuemax="#Model.MaxPlayCount" ...

Multiple data tables involved on one form

Updated 08/14/2012 12:05pm
I will try to explain my situation and hopefully someone can point me in the right direction.
I have a form in my project that will have several tables involved all of the tables are already set up with relationships. Here are the models that are related.
namespace QQAForm.Models
{
public class AuditSchedule
{
public virtual int AuditScheduleID { get; set; }
public virtual Nullable<DateTime> audit_completed_date { get; set; }
public virtual string gl_cmp_key { get; set; }
public virtual string audit_year { get; set; }
public virtual string ar_ship_key { get; set; }
public virtual string ar_ship_name { get; set; }
public virtual string im_adres_city { get; set; }
public virtual string im_adres_state { get; set; }
public virtual string audit_type { get; set; }
public virtual string audit_no { get; set; }
public virtual string audit_group { get; set; }
public virtual string Footage { get; set; }
public virtual string Rolling3MosFootage { get; set; }
public virtual string snp_SalesRep8 { get; set; }
public virtual string epg_sales_rep_accountable { get; set; }
public virtual string tech_service_rep { get; set; }
public virtual string audit_done_by { get; set; }
public virtual Nullable<DateTime> audit_recieved_date { get; set; }
public virtual string audit_notes { get; set; }
public virtual string audit_pdf { get; set; }
public virtual string updated { get; set; }
public virtual string hidden { get; set; }
public virtual string en_stats_key { get; set; }
public virtual string Control_ID { get; set; }
public virtual Nullable<DateTime> audit_date { get; set; }
public virtual string contacts_present { get; set; }
public virtual string audit_furnished_to { get; set; }
public virtual string spacer_type { get; set; }
}
}
MainQuestion:
namespace QQAForm.Models
{
public class MainQuestion
{
public virtual int MainQuestionID { get; set; }
public virtual int SubCategoryID { get; set; }
public virtual int ReferenceNo { get; set; }
public virtual int DisplayIndex { get; set; }
public virtual int SuggestionID { get; set; }
public virtual string Question { get; set; }
public virtual SubCategory SubCategory { get; set; }
public virtual ICollection<Suggestion> suggestions { get; set; }
public virtual ICollection<DocumentLink> documentLink { get; set; }
}
}
Child Questions:
namespace QQAForm.Models
{
public class ChildQuestion
{
public virtual int ChildQuestionID { get; set; }
public virtual int MainQuestionID { get; set; }
public virtual int ReferenceNo { get; set; }
public virtual int DisplayIndex { get; set; }
public virtual string QuestionText { get; set; }
public virtual string UserEntityType { get; set; }
public virtual string UserEntityTexts { get; set; }
public virtual MainQuestion MainQuestion { get; set; }
}
}
Suggestions:
namespace QQAForm.Models
{
public class Suggestion
{
public virtual int SuggestionID { get; set; }
public virtual int MainQuestionID { get; set; }
public virtual int DisplayIndex { get; set; }
public virtual string ReferenceNo { get; set; }
public virtual string Suggestions { get; set; }
public virtual MainQuestion MainQuestion { get; set; }
}
}
Main Answer:
namespace QQAForm.Models
{
public class MainAnswer
{
public virtual int MainAnswerID { get; set; }
public virtual int AuditScheduleID { get; set; }
public virtual int MainQuestionID { get; set; }
public virtual string Score { get; set; }
public virtual string AdditionalNotes { get; set; }
public virtual AuditSchedule AuditSchedule { get; set; }
public virtual MainQuestion MainQuestion { get; set; }
}
}
I am having a difficult time figuring out how to display a question from one table that has a relationship with another table with sub questions and check boxes for the answer. The answers are simple Yes, No, and N/A. They are also held in a different table. The reason i have all of this in data tables is they have to be editable or if i want to add to the areas.
This is what the page should look like. i have incerted text to give the look for the page.
Layout:
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"> </script>
</head>
<body>
<div id="head" class="container">
#Html.Partial("Header")
</div>
<div class="container">
<div id="main">
<ul id="breadcrumbs">
</ul>
<div id="formTopCol">
#RenderBody()
#*#Html.Partial("_Audit")*#
</div>
<div id="formBottomCol">
#Html.Action("_SubCategory")
<div id="formBottomRightCol">
#Html.Action("_Forms")
#*#RenderBody()*#
</div>
<div style="clear:left;"></div>
</div>
</div>
</div>
<div class="container">
#Html.Partial("Footer")
</div>
</body>
</html>
This is what it looks like:
I have set up in the global.asax a string to accept a audit record and then pull the main question. there is a side menu that will select the question area's. This is done in a view where the Audit schedule is the Body and the side menu and form question/answers are Html.Action() for partials.
Global Code:
routes.MapRoute(
"AuditSchedule", // Route name
"AuditSchedule/Audit/{id}/{section}", // URL with parameters
new { controller = "AuditSchedule", action = "Audit", id = UrlParameter.Optional, section = UrlParameter.Optional } // Parameter defaults
);
I have tried to play around with a view model for this but i cannot get this to work. When it comes to databases in C# coding i am really weak.
Here is the Model i am working on with the controller:
namespace QQAForm.ViewModels
{
public class AuditFormEdit
{
public Models.MainAnswer ScoreInstance { get; set; }
public List<ScoreCardCheckBoxHelper> ScoreCardCheckBoxHelperList { get; set; }
public void InitializeScoreCheckBoxHelperList(List<Models.Score> ScoreList)
{
if (this.ScoreCardCheckBoxHelperList == null)
this.ScoreCardCheckBoxHelperList = new List<ScoreCardCheckBoxHelper>();
if (ScoreList != null
&& this.ScoreInstance != null)
{
this.ScoreCardCheckBoxHelperList.Clear();
ScoreCardCheckBoxHelper scoreCardCheckBoxHelper;
string scoreTypes =
string.IsNullOrEmpty(this.ScoreInstance.Score) ?
string.Empty : this.ScoreInstance.Score;
foreach (Models.Score scoreType in ScoreList)
{
scoreCardCheckBoxHelper = new ScoreCardCheckBoxHelper(scoreType);
if (scoreTypes.Contains(scoreType.ScoreName))
scoreCardCheckBoxHelper.Checked = true;
this.ScoreCardCheckBoxHelperList.Add(scoreCardCheckBoxHelper);
}
}
}
public void PopulateCheckBoxsToScores()
{
this.ScoreInstance.Score = string.Empty;
var scoreType = this.ScoreCardCheckBoxHelperList.Where(x => x.Checked)
.Select<ScoreCardCheckBoxHelper, string>(x => x.ScoreName)
.AsEnumerable();
this.ScoreInstance.Score = string.Join(", ", scoreType);
}
public class ScoreCardCheckBoxHelper : Models.Score
{
public bool Checked { get; set; }
public ScoreCardCheckBoxHelper() : base() { }
public ScoreCardCheckBoxHelper(Models.Score scoreCard)
{
this.ScoreID = scoreCard.ScoreID;
this.ScoreName = scoreCard.ScoreName;
}
}
}
}
Controller section:
//get
public ActionResult _Forms(int id)
{
AuditFormEdit viewModel = new AuditFormEdit();
//viewModel.ScoreInstance = _db.MainAnswers.Single(r => r.AuditScheduleID == id);
viewModel.InitializeScoreCheckBoxHelperList(_db.Scores.ToList());
return View(viewModel);
}
//post
[HttpPost]
public ActionResult _Forms(int id, AuditFormEdit viewModel)
{
if (ModelState.IsValid)
{
viewModel.PopulateCheckBoxsToScores();
_db.Entry(viewModel.ScoreInstance).State = System.Data.EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("/");
}
else
{
return View(viewModel);
}
}
As i stated before the ViewModel does not work because i am asking for an id that does not exist. Right now the view model only has code to populate check boxes for the answers.
Added view codes 08/14/2012 1:00pm
Form partial view mostly test but script that compliments the check box code
#{ Layout = null; }
#model QQAForm.ViewModels.AuditFormEdit
<table width="698" border="2" cellpadding="2">
<tr>
<td align="center"><b>Section</b><br />1.0</td>
<td><b>Glass edge damage noted. (shells, flakes, sharks teeth)</b>
<br /><br />
#Html.CheckBox("suggestion1")
It was noted that there was a significant amount of glass edge damage observed on the IG units being produced.
This glass edge damage may lead to a significantly high glass breakage rate in IG unit handling, in the glazing operation and in service.
[MAJOR CONCERN]
The cause of this glass edge damage should be determined and efforts made to eliminate the damage.
<br /><br />
#Html.CheckBox("suggestion2")
The glass edge should be smooth and free of chips, flakes, wings, or other damage. Damaged edges may result in stress cracks or premature IG unit failure.
[MAJOR CONCERN]
<br /><br />
<label>Additional Notes:</label><br />
#Html.TextArea("Additional Notes")
<br />
</td>
<td>
#for (int index = 0; index < Model.ScoreCardCheckBoxHelperList.Count; index++)
{
#Html.CheckBoxFor(m => m.ScoreCardCheckBoxHelperList[index].Checked)
#Html.LabelFor(m => m.ScoreCardCheckBoxHelperList[index], Model.ScoreCardCheckBoxHelperList[index].ScoreName)
#Html.HiddenFor(m => m.ScoreCardCheckBoxHelperList[index].ScoreID)
#Html.HiddenFor(m => m.ScoreCardCheckBoxHelperList[index].ScoreName)
}
</td>
</tr>
</table>
Here is the side menu partial:
#{ Layout = null; }
#model IEnumerable<QQAForm.Models.SubCategory>
<div id="menuCol">
<h3>Audit Sections</h3>
<ul>
<li>
#foreach (var item in Model)
{
<div class="sidemenu">
#Html.ActionLink(item.SubcategoryName, "Audit", new { section = item.SubCategoryID }, null)
</div>
}
</li>
</ul>
</div>
This is the Body:
#model QQAForm.Models.AuditSchedule
#{
ViewBag.Title = "Edit";
Layout = "~/Views/AuditSchedule/_FormLayout.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<table class="audit-display">
<tr>
<th>ID</th>
<th>Customer</th>
<th>City</th>
<th>State</th>
<th>EPG TSM Rep/NAM</th>
<th>EPG RSM (or NAM's VP)</th>
<th>Tech Rep</th>
<th>Audit Type</th>
</tr>
<tr>
<td>#Html.DisplayFor(m => m.AuditScheduleID)</td>
<td>#Html.DisplayFor(m => m.ar_ship_name)</td>
<td>#Html.DisplayFor(m => m.im_adres_city)</td>
<td>#Html.DisplayFor(m => m.im_adres_state)</td>
<td>#Html.DisplayFor(m => m.epg_sales_rep_accountable)</td>
<td>#Html.DisplayFor(m => m.snp_SalesRep8)</td>
<td>#Html.DisplayFor(m => m.tech_service_rep)</td>
<td>#Html.DisplayFor(m => m.audit_type)</td>
</tr>
</table>
<table class="audit-display">
<tr>
<th>Date</th>
<th>Contacts Present</th>
<th>Audit Furnished To</th>
<th>Audit Done By (If not sheduled)</th>
<th>Spacer's Used</th>
</tr>
<tr>
<td>#Html.DisplayFor(m => m.audit_date)</td>
<td>#Html.DisplayFor(m => m.contacts_present)</td>
<td>#Html.DisplayFor(m => m.audit_furnished_to)</td>
<td>#Html.DisplayFor(m => m.audit_done_by)</td>
<td>#Html.DisplayFor(m => m.spacer_type)</td>
</tr>
</table>
</fieldset>
<hr />
}
why are you adding an int id parameter to _Forms HttpPost action? You don't use it so you don't need it then, right? You also don't demonstrate your view code.

Conditional view of fields in a view model in razor

I have the following view model to query my table:
QuestionViewModel.cs
public enum TypeQuestion {
Long = 1,
Short = 2,
Small = 3,
}
public class QuestionViewModel
{
public string Name { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string MaxAge { get; set; }
public string Category { get; set; }
public string Account { get; set; }
public TypeQuestion CurrentTypeQuestion { get; set; }
}
if the query I'm doing is of type:
Long: displays all fields.
Short: displays Name, LastName, Address, MaxAge.
Small: displays Name, LastName.
Is there any way to put some kind of DataAnnotation to determine which fields to display in the view or some other way?, To avoid putting a "what if?" for each field.
Thank you.
This may be overkill, and i'd in fact lean towards #Mystere Man's answer, but this is another option.
Instead of regular primitive types in your ViewModel, set them up to cater for the logic. Looks like Name and LastName are always displayed, whilst Address and MaxAge are conditional.
So, setup your ViewModel like this:
public class QuestionViewModel
{
public string Name { get; set; }
public string LastName { get; set; }
public IEnumerable<ConditionalField> ConditionalFields { get; set; }
public string Category { get; set; }
public string Account { get; set; }
}
public class ConditionalField
{
public string Field { get; set; }
public bool Display { get; set; }
}
In your controller, setup the nested viewmodel and the boolean values for Address and MaxAge ccording to the value of CurrentTypeQuestion.
Then, have your View like this:
/Views/Questions.cshtml
#model QuestionViewModel
#Html.DisplayForModel()
Then create a custom display template (or editor template, if this is a form) for QuestionViewModel:
/Views/DisplayTemplates/QuestionViewModel.cshtml
#model QuestionViewModel
#Html.DisplayFor(model => model.Name)
#Html.DisplayFor(model => model.LastName )
#Html.DisplayFor(model => model.Category)
#Html.DisplayFor(model => model.Account)
#Html.DisplayFor(model => model.ConditionalFields)
Then create another custom display template for ConditionalField:
Views/DisplayTemplates/ConditionalField.cshtml
#model ConditionalField
#if (Model.Display) {
#Html.DisplayForModel()
}
As i said, may be overkill, but in the end, you only have a single if statement in the custom template, no loops, and your main view and first-level template stays clean.
To keep it simple, and avoid complex if logic in your view, just create three different views, with only the data you need in each view. Then select the view in your controller based on the question type.
Based from this link and this link
Controller:
public ActionResult Consulta()
{
return View(new QuestionViewModel());
}
ViewModel:
public enum TypeQuestion {
Long = 1,
Short = 2,
Small = 3,
}
public class QuestionViewModel
{
public string Name { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int MaxAge { get; set; }
public string Category { get; set; }
public string Account { get; set; }
public TypeQuestion CurrentTypeQuestion { get; set; }
public bool EnabledField(ModelMetadata field)
{
//check pending implementation
return true;
}
}
View:
#model MySite.QuestionViewModel
#using System.Linq;
#using System.Collections;
#{
ViewBag.Title = "Question";
Layout = "~/Views/Shared/Layout.cshtml";
}
<h2>Question</h2>
#using (Html.BeginForm(new { id = "FormQuestion" }))
{
foreach (var prop in ViewData.ModelMetadata.Properties
.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm) && ViewData.Model.EnabledField(pm)))
{
if (prop.HideSurroundingHtml)
{
Html.Editor(prop.PropertyName);
}
else
{
<div class="editor-label">
#(prop.IsRequired ? "*" : "")
#Html.Label(prop.PropertyName)
</div>
<div class="editor-field">
#Html.Editor(prop.PropertyName, prop.Model)
#Html.ValidationMessage(prop.PropertyName, "*")
</div>
}
}
}

Categories

Resources