简体   繁体   中英

Accessing a property of a view component from within Controller

I am using a view component for a bit of separation of business logic. I just cant figure out how I pass my id to my controller.

For example I call my view Component here.

@await Component.InvokeAsync("NotesList", new { caseId = Model.Id })

But I want to retrieve the value of caseId in but it appears to be always zero here

[HttpPost]
public async Task<IActionResult> SaveCaseNotes([Bind("Id,Title,Notes,caseId")] MISObjectNotes notes){            
     var testId = notes.MISObjectId;
     if (ModelState.IsValid) {
         _context.Add(notes);
         await _context.SaveChangesAsync();                
        }
        return RedirectToAction("Details");
}

My View Compoennt class as follows

[ViewComponent(Name = "NotesList")]
public class NotesViewComponent : ViewComponent {
    public IViewComponentResult Invoke(int caseId,Guid TennantId) {
        var test = caseId;
        return View();
    }
}

Its this caseId I want to access in my controller how can I achieve that? I was trying going use something like this but it doesn't work.

For anyone else struggling with this I used the session while its not widely used in asp.net core it can still be used.

I used the following as an example, you need to adjust your view components constructor so it injects the session as such.

ViewComponent(Name = "NotesList")]
public class NotesViewComponent : ViewComponent {    
private readonly IHttpContextAccessor _contextAccessor;
   private readonly MISDBContext db;
    public int CaseId { get; set; }
    public NotesViewComponent(MISDBContext context , IHttpContextAccessor contextAccessor) {
        db = context;
        _contextAccessor = contextAccessor;
}

public async Task<IViewComponentResult> InvokeAsync(int caseId) {
  var items = await GetItemsAsync(caseId);            
  _contextAccessor.HttpContext.Session.SetString("CaseId",CaseId.ToString());
return View(items);
}

private Task<List<MISObjectNotes>> GetItemsAsync(int caseId) {
  return db.MISNotes.Where(x => x.isAcitve ==true &&  x.MISObjectId == caseId).ToListAsync();
 }
}

You must add the session however to your Configure section in startup.cs

app.UseSession();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM