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?
Related
I have a variable result which contains a JSON object:
result = JsonConvert.DeserializeObject<PullRequestModel>(responseData);
I would like to use for loop over result as:
#for (var key = 0; key < result.value.length; key++)
{
}
But C# thinks .length is part of the PullRequestModel, and the code is not working.
How do I get around this problem?
This is the PullRequestModel
namespace TestApp.Model.PullRequestModel
{
public class Avatar
{
public string href { get; set; }
}
public class CompletionOptions
{
public string mergeCommitMessage { get; set; }
public bool deleteSourceBranch { get; set; }
public bool squashMerge { get; set; }
public string mergeStrategy { get; set; }
public bool triggeredByAutoComplete { get; set; }
public List<object> autoCompleteIgnoreConfigIds { get; set; }
}
public class CreatedBy
{
public string displayName { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public string id { get; set; }
public string uniqueName { get; set; }
public string imageUrl { get; set; }
public string descriptor { get; set; }
public string href { get; set; }
}
public class Iterations
{
public string href { get; set; }
}
public class LastMergeCommit
{
public string commitId { get; set; }
public string url { get; set; }
}
public class LastMergeSourceCommit
{
public string commitId { get; set; }
public string url { get; set; }
}
public class LastMergeTargetCommit
{
public string commitId { get; set; }
public string url { get; set; }
}
public class Links
{
public Avatar avatar { get; set; }
public Self self { get; set; }
public Repository repository { get; set; }
public WorkItems workItems { get; set; }
public SourceBranch sourceBranch { get; set; }
public TargetBranch targetBranch { get; set; }
public Statuses statuses { get; set; }
public SourceCommit sourceCommit { get; set; }
public TargetCommit targetCommit { get; set; }
public MergeCommit mergeCommit { get; set; }
public CreatedBy createdBy { get; set; }
public Iterations iterations { get; set; }
}
public class MergeCommit
{
public string href { get; set; }
}
public class Project
{
public string id { get; set; }
public string name { get; set; }
public string state { get; set; }
public string visibility { get; set; }
public DateTime lastUpdateTime { get; set; }
}
public class Repository
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public Project project { get; set; }
public string href { get; set; }
}
public class Reviewer
{
public string reviewerUrl { get; set; }
public int vote { get; set; }
public bool hasDeclined { get; set; }
public bool isRequired { get; set; }
public bool isFlagged { get; set; }
public string displayName { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public string id { get; set; }
public string uniqueName { get; set; }
public string imageUrl { get; set; }
public bool isContainer { get; set; }
public List<VotedFor> votedFor { get; set; }
}
public class PullRequestModel
{
public List<Value> value { get; set; }
public int count { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class SourceBranch
{
public string href { get; set; }
}
public class SourceCommit
{
public string href { get; set; }
}
public class Statuses
{
public string href { get; set; }
}
public class TargetBranch
{
public string href { get; set; }
}
public class TargetCommit
{
public string href { get; set; }
}
public class Value
{
public Repository repository { get; set; }
public int pullRequestId { get; set; }
public int codeReviewId { get; set; }
public string status { get; set; }
public CreatedBy createdBy { get; set; }
public DateTime creationDate { get; set; }
public DateTime closedDate { get; set; }
public string title { get; set; }
public string description { get; set; }
public string sourceRefName { get; set; }
public string targetRefName { get; set; }
public string mergeStatus { get; set; }
public bool isDraft { get; set; }
public string mergeId { get; set; }
public LastMergeSourceCommit lastMergeSourceCommit { get; set; }
public LastMergeTargetCommit lastMergeTargetCommit { get; set; }
public LastMergeCommit lastMergeCommit { get; set; }
public List<Reviewer> reviewers { get; set; }
public List<object> labels { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public CompletionOptions completionOptions { get; set; }
public bool supportsIterations { get; set; }
public DateTime completionQueueTime { get; set; }
}
public class VotedFor
{
public string reviewerUrl { get; set; }
public int vote { get; set; }
public string displayName { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public string id { get; set; }
public string uniqueName { get; set; }
public string imageUrl { get; set; }
public bool isContainer { get; set; }
}
public class WorkItems
{
public string href { get; set; }
}
}
This is the cause of the whole problem, if anyone is curious:
#if(result == null)
{
<p> No pull requests found</p>
}
else
{
#foreach (var item in result.value)
{
<div class="accordion">
<input type="checkbox" id="tab1">
<label class="accordion-label" for="tab1"> #item.title </label>
<div class="accordion-content">
<WorkItems PersonalAccessToken="#PersonalAccessToken" WorkItemUrl="#item._links.workItems.href"></WorkItems>
</div>
</div>
}
}
The above code works (it's a Blazor app) I loop trough all Pull requests and show associated Work Items for the PR.
But In order to crete a simple accordion, the I must increment id="tab1"> because in each loop, so my idea was to ditch #foreach and use #for loop, so I can make use of the key to increment the value of id="tab1">
Hope it makes sense
result = JsonConvert.DeserializeObject<PullRequestModel>(responseData);
#for (var key = 0; key < result.value.Count; key++)
{
}
List<> exposes the Count property not Length property.
It would appear you are deserializing a single object and not an enumerable type. Please try using the following if you want to return something to loop through:
result = JsonConvert.DeserializeObject<List<PullRequestModel>>(responseData);
#for (var key = 0; key < result.Count; key++)
{
}
Count is a property of of the List object in this case.
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.
I have created an API that I am now attempting to access through another application. Even though I am using Newtonsoft.JSON to both serialize and deserialize the JSON, I am encountering a conversion error, with the following InnerException:
{"Could not cast or convert from System.String to System.Collections.Generic.List`1[MidamAPI.Models.ManagerDTO]."}
The following is the snippet that throws the error (in RESTFactory):
public List<T> Execute<T>(String endPoint) where T : new() {
RestClient client = new RestClient(BASE_URL);
IRestRequest req = new RestRequest(endPoint);
req.AddHeader("Authorization", "Bearer " + this._token);
var response = client.Execute(req).Content;
List<T> responseData = JsonConvert.DeserializeObject<List<T>>(response);
return responseData;
}
which is called here:
{
RegisterViewModel vm = new RegisterViewModel();
RESTFactory factory = new RESTFactory((String)Session["bearer"]);
vm.availableManager = factory.Execute<ManagerDTO>("managers");
vm.availableProperties = factory.Execute<PropertyDTO>("locations");
vm.availableTrainers = factory.Execute<TrainerDTO>("trainers");
return View(vm);
}
The information is coming from the following API controller action (in a separate application):
[LocalFilter]
[RoutePrefix("managers")]
public class ManagersController : ApiController
{
UnitOfWork worker = new UnitOfWork();
[Route("")]
public string Get()
{
IEnumerable<ManagerDTO> dtoList = Mapper.Map<List<Manager>, List<ManagerDTO>>(worker.ManagerRepo.Get().ToList());
foreach (ManagerDTO dto in dtoList)
{
Manager manager = worker.ManagerRepo.GetByID(dto.ID);
dto.Stores = (Mapper.Map<IEnumerable<Property>, IEnumerable<PropertyDTO>>(manager.Properties)).ToList();
}
return JsonConvert.SerializeObject(dtoList);
}
The DTOs are the same in both applications:
{
public class ManagerDTO
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<PropertyDTO> Stores { get; set; }
}
public class PropertyDTO
{
public int ID;
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public string TrainerEmail { get; set; }
}
I tried using the json2csharp tool with the response, and everything seems fine to my eyes:
public class Store
{
public int ID { get; set; }
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public object TrainerEmail { get; set; }
}
public class RootObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Store> Stores { get; set; }
}
Any advice would be appreciated.
EDIT:
The RegisterViewModel class
public class RegisterViewModel
{
public RegistrationDTO regModel { get; set; }
public List<ManagerDTO> availableManager { get; set; }
public List<PropertyDTO> availableProperties { get; set; }
public List<TrainerDTO> availableTrainers { get; set; }
}
Make your controller Get() return type
IHttpActionResult
and return
Ok(dtoList);
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.
im trying to deserialize a Json that i get from a webservice Like so:
Uri urlJson = new Uri("http://optimizingconcepts.com/staging/cartuxa/system/json_request.php?lang=pt");
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(urlJson);
var jsonString = await response.Content.ReadAsStringAsync();
the Json i get is this:http://paste2.org/MpYJd8kk
I then do this to get the JsonObject:
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
What i want to know, is the correct way of saving each object from json to a list
so the objects from "home" would be in a List, the objects from "artigos" would go to a List and so on.
Using Json.Net, it can be done as follows
Uri urlJson = new Uri("http://optimizingconcepts.com/staging/cartuxa/system/json_request.php?lang=pt");
var client = new HttpClient();
var json = await client.GetStringAsync(urlJson);
var obj = JsonConvert.DeserializeObject<Cartuxa.RootObject>(json);
I used http://json2csharp.com/ to generate below classes.
public class Cartuxa
{
public class Home
{
public object id { get; set; }
public string menu { get; set; }
public string title { get; set; }
public string image { get; set; }
public string url { get; set; }
}
public class Artigo
{
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public List<object> media { get; set; }
}
public class Year
{
public string year { get; set; }
public string title { get; set; }
public string description { get; set; }
public string file { get; set; }
public string url { get; set; }
}
public class Product
{
public string id { get; set; }
public string image { get; set; }
public string url { get; set; }
public List<Year> year { get; set; }
}
public class Vinho
{
public string id { get; set; }
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public List<Product> product { get; set; }
}
public class Year2
{
public string year { get; set; }
public string title { get; set; }
public string description { get; set; }
public string file { get; set; }
public string url { get; set; }
}
public class Product2
{
public string id { get; set; }
public string image { get; set; }
public string url { get; set; }
public List<Year2> year { get; set; }
}
public class Azeite
{
public string id { get; set; }
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public List<Product2> product { get; set; }
}
public class Agente
{
public string id { get; set; }
public string continent_id { get; set; }
public string country_id { get; set; }
public string title { get; set; }
public string description { get; set; }
}
public class Continente
{
public string id { get; set; }
public string title { get; set; }
}
public class Pais
{
public string id { get; set; }
public string continent_id { get; set; }
public string title { get; set; }
}
public class Contacto
{
public string id { get; set; }
public string menu_id { get; set; }
public string submenu_id { get; set; }
public string title { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
public class Premio
{
public string image { get; set; }
public string url { get; set; }
}
public class Noticia
{
public string id { get; set; }
public string menu { get; set; }
public string date_created { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public List<object> media { get; set; }
}
public class RootObject
{
public List<Home> home { get; set; }
public List<Artigo> artigos { get; set; }
public List<Vinho> vinhos { get; set; }
public List<Azeite> azeites { get; set; }
public List<Agente> agentes { get; set; }
public List<Continente> continentes { get; set; }
public List<Pais> paises { get; set; }
public List<Contacto> contactos { get; set; }
public List<Premio> premios { get; set; }
public List<Noticia> noticias { get; set; }
}
}