Populating a page with data from a database in mvc 5 - c#

I would like to populate certain parts of a view with certain fields from a database. I'm not sure exactly how to make this work. This is my current situation...
Here is my controller action:
public ActionResult Course_page(string id)
{
string abbrev = id;
var cpage = from c in db.Course_page
select c;
if (!String.IsNullOrEmpty(abbrev))
{
cpage = cpage.Where(x => x.abbrev.Contains(abbrev));
}
return View(cpage);
}
My Model:
[Table("course_page")]
public class Course_page
{
[Key]
public int CourseID { get; set; }
public string Meta { get; set; }
public string Title { get; set; }
public string Country { get; set; }
public string main_image { get; set; }
public string list_1 { get; set; }
public string list_2 { get; set; }
public string list_3 { get; set; }
public string list_4 { get; set; }
public string list_5 { get; set; }
public string list_6 { get; set; }
public string list_7 { get; set; }
public string list_8 { get; set; }
public string list_9 { get; set; }
public string list_10 { get; set; }
public string testim_1 { get; set; }
public string testim_2 { get; set; }
public string testim_3 { get; set; }
public string course_site { get; set; }
public string popup_script { get; set; }
public string abbrev { get; set; }
}
The view (shortened):
#model IEnumerable<oltinternational_mvc.Models.Course_page>
<div id="main_container">
<article class="content">
<h1>{#Html.DisplayNameFor(modelItem => cpage.Title)}</h1>
</article>
</div>
I get that I have to reference the cpage variable somewhere on the view but I'm not sure exactly in what manner. The idea is that the course page will load with the correct details as per the ID provided by the URL.
Please could someone advise me how I am to include the cpage variable in the view file or if I am doing this the correct way at all?

You are doing it correct way just change this helper :
{#Html.DisplayNameFor(modelItem => cpage.Title)} to
#Html.DisplayNameFor(modelItem => modelItem .Title)
And print the data in foreach loop because you can have more than one result.

Related

Partial View not binding with the model

I have main view binding to custom model with two partial views. One partial view is binding to schedule model and other to the same custom model.
The second partial view is showing null on http posting.
This is the Main View
#model DBS.CustomVariable
<div id="divSchedule" style="display: none" align="left">
#Html.Partial("_cron", new DBS.Schedule2())
#Html.Partial("ScheduleEditPartial" ,Model)
</div>
The view model is like this
namespace DBS
{
public class CustomVariable
{
public int ReportId { get; set; }
public string ReportName { get; set; }
public string ReportTypeId { get; set; }
public string TemplateLocation { get; set; }
public bool IsScheduled { get; set; }
public int ScheduleID { get; set; }
public string MailCC { get; set; }
public string MailBCC { get; set; }
public string MailSubject { get; set; }
public string MailBody { get; set; }
public string MailTo { get; set; }
public bool Status { get; set; }
public bool IsReportNameOverwrite { get; set; }
public string NamingConvention { get; set; }
public string FileAttribs { get; set; }
public string[] DirectoryName { get; set; }
public List<string> FolderName { get; set; }
public string SavePath { get; set; }
[RegularExpression("^[a-zA-Z][a-zA-Z0-9_]*$", ErrorMessage = "Please start with alphabets followed by alphanumeric or _.")]
[StringLength(20)]
public string FilePath { get; set; }
public string DefaultLocation => ConfigurationManager.AppSettings["DefaultExcelReportSavePath"];
public int ShareOption { get; set; }
public string[] station_arr { get; set; }
public string TemplateOriginalName { get; set; }
}
}
And the controller is this
[ValidateInput(false)]
[System.Web.Mvc.HttpPost]
[Authorize(Roles = "ExcelCreate")]
[SessionExpireFilter]
public ActionResult Create(FormCollection form, HttpPostedFileBase file, CustomVariable modelCustomVariable)
{......}
I am getting null values in the customvariable in controller method.
Where am i missing?

asp.net core automapper ViewModel to Model

I'm following some examples to learn asp.net core with Entity Framework, I'm having trouble saving a user's data, I have the class that was generated from an existing database (Database First), and created a ViewModel to work with the views, my class generated from the database came with some dependencies, "ICollection", I just need to update some fields of the table, when I try to save the error occurs below:
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
SqlException: String or binary data would be truncated.
The statement has been terminated.
My Model:
using System;
using System.Collections.Generic;
namespace PetAlerta.Domain.Entities
{
public partial class Petshop
{
public Petshop()
{
Agendabanhos = new HashSet<Agendabanhos>();
Agendaconsultas = new HashSet<Agendaconsultas>();
Agendavacinas = new HashSet<Agendavacinas>();
Banhos = new HashSet<Banhos>();
Chat = new HashSet<Chat>();
Configshop = new HashSet<Configshop>();
Consultas = new HashSet<Consultas>();
Pets = new HashSet<Pets>();
Shopdonos = new HashSet<Shopdonos>();
}
public int Cod { get; set; }
public string Razaosocial { get; set; }
public string Nomefant { get; set; }
public string Cnpj { get; set; }
public string Endereco { get; set; }
public string Cidade { get; set; }
public string Uf { get; set; }
public string Complemento { get; set; }
public string Bairro { get; set; }
public string Num { get; set; }
public string Cep { get; set; }
public string Endecomp { get; set; }
public string Email { get; set; }
public string Fone1 { get; set; }
public string Fone2 { get; set; }
public string Celular { get; set; }
public string Senha { get; set; }
public string Img { get; set; }
public string Nomeresp { get; set; }
public string Site { get; set; }
public string Seguimento { get; set; }
public DateTime? Dataacesso { get; set; }
public int Ativo { get; set; }
public ICollection<Agendabanhos> Agendabanhos { get; set; }
public ICollection<Agendaconsultas> Agendaconsultas { get; set; }
public ICollection<Agendavacinas> Agendavacinas { get; set; }
public ICollection<Banhos> Banhos { get; set; }
public ICollection<Chat> Chat { get; set; }
public ICollection<Configshop> Configshop { get; set; }
public ICollection<Consultas> Consultas { get; set; }
public ICollection<Pets> Pets { get; set; }
public ICollection<Shopdonos> Shopdonos { get; set; }
}
}
My ViewModel:
using System.ComponentModel.DataAnnotations;
namespace PetAlerta.MVC.ViewModels
{
public class PetShopViewModel
{
[Key]
public int Cod { get; set; }
public string Razaosocial { get; set; }
public string Nomefant { get; set; }
public string Cnpj { get; set; }
public string Endereco { get; set; }
public string Cidade { get; set; }
public string Uf { get; set; }
public string Complemento { get; set; }
public string Bairro { get; set; }
public string Num { get; set; }
public string Cep { get; set; }
public string Endecomp { get; set; }
public string Email { get; set; }
public string Fone1 { get; set; }
public string Fone2 { get; set; }
public string Celular { get; set; }
public string Nomeresp { get; set; }
public string Site { get; set; }
}
}
I'm using the automapper to map the Model to the ViewModel and the ViewlModel to the Model.
Controller:
[HttpPost]
public IActionResult SalvaPerfil([FromBody] PetShopViewModel petshopViewModel)
{
if (ModelState.IsValid)
{
var petshop = Mapper.Map<PetShopViewModel, Petshop>(petshopViewModel);
_PetApp.Update(petshop);
return Content("fim..."); //<<=== ERROR
}
return Content("ERRO");
}
I just want to update the fields that is in the ViewModel, other fields like password, image url etc ... I want to update separately at another time, where am I going wrong? how to do this?
Thanks!
Error is very clear. Just check the columns length and properties value, you'll find that the length of one or more fields is NOT big enough to hold the data you are trying to insert. For example, if one field is a varchar(8) length, and you try to add 10 characters in to it, you will get this error.

IList dataset insert to database table

I'm getting data set to POST action method's model object like following
Once I expand above object , it has following properties
Once I expand above ListProductFields IList , it has following properties
Once I expand above ListProductFields IList's object values , [0]th value it has following properties and its values
this is the relevant model class files
public class AddNewProduct
{
public string Product_ID { get; set; }
public string ProductTypeID { get; set; }
public string ProductCategoryID { get; set; }
public string Subsidary_ID { get; set; }
public string Field_ID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public string ApprovalStatus { get; set; }
public string Status { get; set; }
public IList<AB_ProductTypeCategoryField> ListProductFields { get; set; }
}
public partial class AB_ProductTypeCategoryField
{
public string ProductFieldID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public string ProdcutFieldDiscriptionEn { get; set; }
public string ProductFieldDiscriptionAr { get; set; }
public string Status { get; set; }
public bool IsChecked { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public string Field_Value_EN { get; set; }
public string Field_Value_AR { get; set; }
}
public partial class AB_Product_vs_Field
{
public string Product_ID { get; set; }
public string Field_ID { get; set; }
public string Field_Value_EN { get; set; }
}
I have database table call AB_Product_vs_Field and I want to insert ,
ProductFieldID ,Field_ID , Field_Value_EN from those values from last image
since these are 19 objects have to insert to the AB_Product_vs_Field database table I may have to use a loop .
so I created following linq query to insert data to that table
[HttpPost]
[ValidateInput(false)]
public ActionResult Add_Product(AddNewProduct product)
{
AB_Product_vs_Field insertproductvalue = new AB_Product_vs_Field();
if (ModelState.IsValid)
{
for (int i = 0; i < product.ListProductFields.Count; i++)
{
insertproductvalue.Product_ID = product.Product_ID;
insertproductvalue.Field_ID = product.ListProductFields[i].ProductFieldID;
insertproductvalue.Field_Value_EN = product.ListProductFields[i].Field_Value_EN;
};
db.AB_Product_vs_Field.Add(insertproductvalue);
db.SaveChanges();
}
}
but I'm getting following error
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I put debug point in front of this line db.AB_Product_vs_Field.Add(insertproductvalue); of my code.once this line calling its directing to following section in App_Browsers.9u0xu-_o.0.cs file
public class ApplicationBrowserCapabilitiesFactory : System.Web.Configuration.BrowserCapabilitiesFactory {
public override void ConfigureCustomCapabilities(System.Collections.Specialized.NameValueCollection headers, System.Web.HttpBrowserCapabilities browserCaps) {
}
this is the error page I'm getting once this line called
these are the images of error
Image 1:
Image 2:
I added the following line in the for loop, then it can keep a record of every tuple
#Html.HiddenFor(m => m.ListProductFields[i].ProductFieldID)
then my view page appeared like this
<div class="col-md-10">
#Html.HiddenFor(m => m.ListProductFields[i].ProductFieldID)
#Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_EN,
new { #class = "form-control summernote", #row = 5 })
</div>

Im trying to get the last record submitted in the db using the repository pattern and MVC

Im trying to get the last record submitted in the db using the repository pattern and MVC. I am attaching the interface and class.And the controller where you can put the code. Please let me know if you need more details. Thanks.
public interface IRequestRepository
{
tblRequest GetCaseId(int caseId);
}
public class RequestRepository: IRequestRepository
{
helpdeskEntities context = null;
public RequestRepository()
{
context = new helpdeskEntities();
}
public string GetCaseId(Ticket ticket)
{
string caseId = string.Empty;
tblRequest tr = context.tblRequests.Where(u => u.CaseID == ticket.CaseID && u.UEmailAddress == ticket.UEmailAddress).SingleOrDefault();
if (tr != null)
{
caseId = tr.CaseID;
}
return caseId;
}
}
public class Ticket
{
public int CaseID { get; set; }
public string Title { get; set; }
[Required]
public string UFirstName { get; set; }
[Required]
public string ULastName { get; set; }
//public string UDisplayName { get; set; }
[Required]
public string UDep_Location { get; set; }
[Required]
public string UEmailAddress { get; set; }
//public string UComputerName { get; set; }
//public string UIPAddress { get; set; }
[Required]
public string UPhoneNumber { get; set; }
[Required]
public string Priority { get; set; }
[Required]
public string ProbCat { get; set; }
//public string IniDateTime { get; set; }
//public string UpdateProbDetails { get; set; }
//public string UpdatedBy { get; set; }
public string InitiatedBy_tech { get; set; }
public string AssignedBy { get; set; }
public string TechAssigned { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string ProbDetails { get; set; }
}
Controller
public ActionResult CreateTicket(tblRequest td)
{
}
First, you need to upgrade your IRequestRepository and add that method:
(I am assuming you're using EntityFramework for that)
public IRequestRepository
{
Request Latest(Ticket ticket);
}
Next, you need to implement that method in your RequestRepository:
public class RequestRepository : IRequestRepository
{
/* other code here */
public Request Latest(Ticket ticket)
{
// I'm also assuming you're using an auto incremented CaseId
return this.context.tblRequests.OrderByDescending(p => p.CaseId).FirstOrDefault(p => p.UEmailAddress == ticket.UEmailAddress);
}
}
And another thing:
Your IRequestRepository.GetCaseId implementation returns a string while it should return a tblRequest (one would also expect it to return an int Id...)
Anyway, I hope this helps!

Mapping JSON data to model and back in MVC 4

Pardon any misspeaking I may do. I am just learning asp.net c#, OOP, and MVC 4.
I am using the Annotator plugin on my site and I am trying to store and retrieve the results from a data base. When a new annotation is created it sends information like this to the controller.
{
"text":"asdas sd a dasd as dasd",
"ranges":
[{
"start":"/div/p[3]",
"startOffset":195,
"end":"/div/p[3]",
"endOffset":532
}],
"quote":"Some quote that was selected.",
"UserID":"1",
"ProjectDocID":"1"
}
Now, I hoped something like this would load all the data into a nice easy object.
// GET: /Annotation/Create
public ActionResult Create(Comment comment)
{
db.Comments.Add(comment);
db.SaveChanges();
return Json(comment);
}
The model I had looked like this (and I am change it however it needs to be changed).
public class Comment
{
[Key]
public int CommentID { get; set; }
public int ProjectDocID { get; set; }
public int UserID { get; set; }
public string text { get; set; }
public string Annotation { get; set; }
public string quote { get; set; }
public string start { get; set; }
public string end { get; set; }
public string startOffset { get; set; }
public string endOffset { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<CommentVote> CommentVote { get; set; }
public virtual ICollection<CommentReply> CommentReply { get; set; }
public ProjectDoc ProjectDoc { get; set; }
public virtual User User { get; set; }
}
What do I need to do to get the data from the server and map it to the model. I also need to be able to send it back in the format at the top so the plugin understands it when it asks for it from the Details action in the controller.
Not sure if this is the right way to do it or not, but it lets me store it in the database and that's all that matter for the moment. I updated my model as follows.
public class Comment
{
[Key]
public int CommentID { get; set; }
public int ProjectDocID { get; set; }
public int UserID { get; set; }
public string text { get; set; }
public string quote { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<CommentVote> CommentVote { get; set; }
public virtual ICollection<CommentReply> CommentReply { get; set; }
public ProjectDoc ProjectDoc { get; set; }
public virtual User User { get; set; }
public List<ranges> ranges { get; set; }
}
public class ranges {
public int ID { get; set; }
public string start { get; set; }
public string end { get; set; }
public string startOffset { get; set; }
public string endOffset { get; set; }
}
This matches the JSON object I am sending in to the controller with Ajax. Once it matches exactly the controller action above works.

Categories