I try pass model data between two Razor pages, data is not string or bool or int
data that i want pass to second page is a model,
i do taht with this way,
public class AskLibrarian
{
public int Id { get; set; }
public string FullName { get; set; }
public string Subject { get; set; }
public string Email { get; set; }
public string Text { get; set; }
public string UserIp { get; set; }
public DateTime CreateDate { get; set; }
public bool ReadIt { get; set; }
public bool Answer { get; set; }
public string reciptCode { get; set; }
}
And on Get method pass data with this way:
[BindProperty]
public AskLibrarian AskLibrarian { get; set; }
public async Task<IActionResult> OnPostQuestionAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
AskLibrarian.Answer = false;
AskLibrarian.CreateDate = DateTime.Now;
AskLibrarian.ReadIt = false;
string userIp = $"{ HttpContext.Connection.RemoteIpAddress}";
if (string.IsNullOrEmpty(userIp))
{
userIp = "127.0.0.1";
}
AskLibrarian.UserIp = userIp;
string rndNuber = Business.RandomNumberForQuestion.randCode;
AskLibrarian.reciptCode = rndNuber;
await _emailSenderService.SendEmailAsync(AskLibrarian.Email, AskLibrarian.FullName, rndNuber);
_context.AskLibrarians.Add(AskLibrarian);
await _context.SaveChangesAsync();
Message = "your message sended";
//return RedirectToPage("/Subfolder/Index", new { SFId = 7 });
return RedirectToPage("/Subfolder/AskLibrarianCode", new { asklib = AskLibrarian });
}
In post method in second page, like to get data on this way:
public void OnGet(Model.AskLibrarian asklib)
{
askLibrarianVM = new AskLibrarianVM
{
Answered = false,
CreateDate = asklib.CreateDate,
LastUpdate = asklib.CreateDate,
RandomeCode = asklib.reciptCode,
Status = false,
};
}
But asklib is empty ,I set a breakpoint at end of Get method and I sow that asklib if filled with valid values but in post method when i try to get data, asklib is empty
what is my mistake
The simple answer was :
return RedirectToPage("/Subfolder/AskLibrarianCode", AskLibrarian );
My mistake was
... new{asklib = AskLibrarian});
After more than two hours
The lowest friction way is to return View("SomeViewForTheModel", AskLibrarian) and do your thing with a completely different view. Your second page controller action really isn't doing anything.
Otherwise, you'll have to save the ID associated with your AskLibrarian object, presumably in a database, and then look it up on the second page either by putting the ID in the URL path (be sure to validate the user should see it!), or by looking up in the database whatever is owned by the user.
Related
I got an error while getting json data from POST method, am I doing something wrong
C# Code:
public IActionResult signupapi(UserSignUp user)
{
var model = new Models.SignUpModelAPI(HttpContext);
if (user == null)
{
return Content(model.ResponseJsonText(false, string.Format(model.Language("empty"),
HttpContext.Request.Method, HttpContext.Request.Path.Value), Class.CodeResponse.ERROR), new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
if (!model.isAllowMethod("POST"))
{
return Content(model.ResponseJsonText(false,string.Format(model.Language("notallowmethod"),
HttpContext.Request.Method,HttpContext.Request.Path.Value),Class.CodeResponse.ERROR),new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
return Content(JsonConvert.SerializeObject(user));
}
public class UserSignUp
{
public string fullname { get; set; }
public string username { get; set; }
public string email { get; set; }
public string password { get; set; }
}
And this is the result when i try on reqbin every value i get is null
You need to add FromBody attribute to get your data for the POST operation:
public IActionResult signupapi([FromBody]UserSignUp user)
You can read more on parameter binding on MSDN docs.
I have a web api built in .NET, within an endpoint i would like to redirect to an url which matches the the code inserted in database. the endpoint takes as entry the code and i am supposed to redirect to the corresponding url. For that i use the Redirect method which actually is not working. i did Console.Write to print if the url is null or empty but it exists. here is the code of my controller :
[HttpGet("{hash}")]
// [ProducesResponseType(302)]
//[ProducesResponseType(404)]
public async Task<IActionResult> redirectUrl(string hash)
{
var t = await new ServiceUrl(_ctx).GetTarget2(hash);
int a = 0;
foreach (Model.Data.DAO.Url i in t)
{
if (i != null)
{
a=a+1;
}
}
if (a==0)
{
return new TimeoutExceptionObjectResult(error: "Not Found",503);
}else
if (DateTime.Compare(DateTime.Now, t.ElementAt(0).ExpireAt) > 0)
{
t.ElementAt(0).state = "expire";
_ctx.Entry(t.ElementAt(0)).State = EntityState.Modified;
await _ctx.SaveChangesAsync();
return new TimeoutExceptionObjectResult(error: "Url expiré",501);
}
string url= t.ElementAt(0).UrlOrigin;
Console.Write(url);
return new Redirect(url);
}
the GetTarget2 method :
public async Task<IEnumerable<Url>> GetTarget2(string hash)
{
var t2 = await _ctx.Url.Where(u => u.UrlShort == hash).ToArrayAsync();
return t2;
}
and the entity :
[Table("Url")]
public class Url
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UrlShort { get; set; }
public string UrlOrigin { get; set; }
public string state { get; set; }
public int Customer_id { get; set; }
public int? targetItemId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ExpireAt { get; set; }
[JsonIgnore]
public List<Stats> GetStats { get; set; }
public Url()
{
}
public Url(int Id,string UrlShort,string UrlOrigin,string state,int Customer_id,DateTime CreatedAt,DateTime ExpireAt)
{
this.Id = Id;
this.UrlShort = UrlShort;
this.UrlOrigin = UrlOrigin;
this.state = state;
this.Customer_id = Customer_id;
this.CreatedAt = CreatedAt;
this.ExpireAt = ExpireAt;
}
}
when i try to pass a code which is in database i get this : Not found which means it does not find it in database
Update:
the database context declaration :
private readonly DatabaseContext _ctx;
and its definition :
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Url> Url { get; set; }
public DbSet<User> User { get; set; }
public DbSet<Stats> Stats { get; set; }
}
If I understood your question correctly then you are trying to redirect to another action method by reading the URL from the database. If the retured Url belongs to your application and just have the dynamic parameter then you can try RedirectToAction method for the redirect.
Syntax:
return RedirectToAction("ActionName", new { id = 90 });
The will cause a redirect to YourApp/Controller/ActionName/90
All you have to create an action method with argument (if required) and redirect from another action method from where you are getting url.
Alternativly you can also use
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "NameOfController", action = "Index", id = id } )
);
The problem was the Redirect method which indicates its content was null or empty although i printed the url in terminal successfully. So What i did is adding a prefix (http://) like this Redirect("http://"+url), url is the url coming from the database. if the url already contains the prefix http or https i remove it before passing it as parameter inside Redirect method. Doing this solved my problem.
eWhy is my Icollection foreign key always blank I have a foreign table called photos which I have created using the Icollection. Im using ef core 3.1.7 and asp.net core 3.1 how does one get the file attachments VesselsId not to be null
Basically one vessel can have many photos but their could also be many vessels.
public class Vessels {
public int Id { get; set; }
[StringLength(400)]
public string Name { get; set; }
public string FlagName { get; set; }
public ICollection<FileAttachments> PhotosAttachments { get; set; }
}
This is the file attachments
public class FileAttachments {
public int Id { get; set; }
public string Title { get; set; }
public string File { set; get; }
}
In where I Wish to display the photos their blank I use the include statement to try and include them in my query.
var vessels = await _context.Vessels.Where(w=>w.Id==id).Include(c=>c.PhotosAttachments).FirstAsync();
But If I look here it will show PhotosAttachments being of null when I look at the field value sure enough its sitting there null.
I think i need to do something here but im not sure as to what
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
}
Edit 2
Basically i have a generic Upload Files method as such which is called via the submit button
[HttpPost]
public async Task<IActionResult> UploadFiles(List<IFormFile> FormFile, int UploadArea, int PoiId, int VesselId) {
FileAttachments attachments = new FileAttachments {
DocumentPath = filePath,
UploadAreaId = UploadArea,
CaseId = resultCaseId,
FullPath = savedFileName,
FileSize = infoFile.Length,
OrignalFileName = fileAttachments.FileName,
FileAttachmentType = fileAttachmentType,
TennantId = await GetCurrentTennantId(),
Extension = infoFile.Extension.Replace(".", "").ToLower(),
UploadedBy = caseOfficer.Id,
CreatedDate = DateTime.Now,
File = uniqueFilename,
ContentType = fileAttachments.ContentType,
isActive = true,
isDeleted = false
};
if (PoiId != 0) {
attachments.PoiID= PoiId;
}
if (VesselId != 0) {
attachments.VesselId = VesselId;
}
_context.Add(attachments);
await _context.SaveChangesAsync();
}
There is some confusion above i am using to store something else the
collection does not create this field it creates VesselsId with the
extra s this is what is not being filled in.
public int? VesselId { get; set; }
The collection creates this field
Add relation to FileAttachments model like this
public class FileAttachments {
...
[ForeignKey("Vessels")]
public int? VesselId { get; set; }
public Vessels Vessels { get; set; }
}
[HttpGet("/api/notes/suggested")]
public JsonResult GetSuggestedNotes(string searchText)
{
//TODO: Podpowiedzi przy wpisywaniu tytułu
JsonResult result = null;
try {
List<Note> n = db.Notes.Include(x => x.NoteTags).ToList();
result = Json(n);
}
catch(Exception e)
{
Console.WriteLine(e);
}
return result;
}
public class Note
{
public Note()
{
CreationDate = DateTime.Now;
NoteTags = new HashSet<NoteTag>();
Parts = new HashSet<Part>();
}
public int ID { get; set; }
public virtual ICollection<NoteTag> NoteTags { get; set; }
public virtual ICollection<Part> Parts { get; set; }
public DateTime? CreationDate { get; set; }
[NotMapped]
public string TagsToAdd { get; set; }
[NotMapped]
public string TagsAsSingleString {
get
{
string result = "";
foreach(var nt in NoteTags)
{
result += nt.Tag.Name + " ";
}
return result;
}
}
}
public class NoteTag
{
public int NoteId { get; set; }
public virtual Note Note { get; set; }
public int TagId { get; set; }
public virtual Tag Tag { get; set; }
}
When I try to get data using this WebAPI controller, I get 502 bad gateway. No errors, everything's fine while debugging server. Data get from database correctly.
I suspect that it could be something similar to "infinite loop" but how to prevent it? (Note class is connected to collection of NoteTag objects that are connected back to Note which probably makes this loop).
And why there are no errors if something went wrong? :/
I don't know if it still relevant but i had the same problem and what worked for me it to Configure Newtonsoft.Json
SerializerSettings.ReferenceLoopHandling = ewtonsoft.Json.ReferenceLoopHandling.Ignore.
If you are using VS2015 MVC you can add the following code:
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
in the ConfigureServices method in the Startup class.
I think the problem its recursion, can you try with an Anonymous type
NoteTags has Note , imagine if the Note->NoteTags->Note->NoteTags->Note->NoteTags ...
`List n = db.Notes.Include(x => x.NoteTags).ToList();
var e = n.select(x=> new {property=value});
result = Json(e);`
I create an new Contractor object "gc" that calls a method GetContractor() to return all the properties. The results it is returning is correct, however the "gc" object shows all "NULL". I assume I doing something incorrectly in my aspx.cs page?
aspx.cs
protected void fvWasteCollected_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert")){
ValidationSummaryWasteDetail.ValidationGroup = "WasteReceivedDetail";
if (IsValid) {
odsMRWWasteCollectedDetail.InsertParameters["WasteTypeId"].DefaultValue = ddlWasteCollectedType.SelectedValue;
odsMRWWasteCollectedDetail.InsertParameters["DisposalMethodId"].DefaultValue = ddl_disposalMethod.SelectedValue;
Contractor gc = new Contractor();
gc.GetContractor(2);
var contractorName = gc.MRWContractorName;
}
}
}
.cs
public class Contractor
{
public Contractor GetContractor(int MRWContractorId)
{
using (DataAccessLINQDataContext db = new DataAccessLINQDataContext())
{
var result = db.MRWContractors.Where(c => c.MRWContractorId == MRWContractorId).Select(c => new Contractor
{
MRWContractorId = c.MRWContractorId,
MRWContractorName = c.MRWContractorName,
MRWContractorAddress = c.MRWContractorAddress,
MRWContractorCity = c.MRWContractorCity,
MRWContractorStateCode = c.MRWContractorStateCode,
MRWContractorZipCode = c.MRWContractorZipCode,
MRWContractorPhone = c.MRWContractorPhone,
MRWContractorFax = c.MRWContractorFax,
MRWContractorEmail = c.MRWContractorEmail
}).SingleOrDefault();
return result;
}
}
public int MRWContractorId { get; set; }
public string MRWContractorName { get; set; }
public string MRWContractorAddress { get; set; }
public string MRWContractorCity { get; set; }
public string MRWContractorStateCode { get; set; }
public int? MRWContractorZipCode { get; set; }
public string MRWContractorPhone { get; set; }
public string MRWContractorFax { get; set; }
public string MRWContractorEmail { get; set; }
}
You are loosing the value of gc when you dont assign it to something.
Try this instead:
var contractor = gc.GetContractor(2);
var contractorName = contractor.MRWContractorName;
You are creating one empty instance of the object that is only used to call the GetContractor method. The GetContractor method creates another instance that contains data, which is returned, but you just throw that instance away and expect the data to be available in the first instance that never got populated.
Make the GetContractor method static so that you don't need an instance to call it:
public static Contractor GetContractor(int MRWContractorId)
Now you can call the method to get that instance that contains the data, without first creating an empty instance:
Contractor gc = Contractor.GetContractor(2);
string contractorName = gc.MRWContractorName;