Hello guys I have a problem in the Account Controllers wanted to add a method for viewing jobs for employees, but now it is giving me an error "Not all code paths return a value"
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
}
Your method's return type is ActionResult
public ActionResult ViewAssignJob()
{
}
In these type of method you generally return View() or return View(viewmodel).
If you don't want to return view for some debugging purpose, you could also return content("hello world") this will result to Hello world in a blank page
Return View() from Actionresult and your error will gone.
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
return View(); // or // return View(Model);
}
hey you just forgot one important line as your error suggest, just put a return statement in your method so that it returns what you want. after this I am sure you will not be experiencing any problem.
here is how your code should look like!
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
return View(jobs);
}
Related
I just want to get my ApplicationUser in MVC. I'm trying this code:
public async System.Threading.Tasks.Task<ApplicationUser> GetApplicationUser()
{
return await _userManager.GetUserAsync(HttpContext.User);
}
var user = GetApplicationUser();
var user2 = user.Result;
However, when I try to access user.Result I get exception
"One or more errors occurred. (Object reference not set to an instance of an object.)"
"Object reference not set to an instance of an object."
Not sure how to access the result.
Make sure you controller action is aync Task, like so:
public async Task<IActionResult> Test()
{
ApplicationUser user = await GetCurrentUserAsync();
if (user != null) {
// do more stuff here
}
// do more stuff here
return View();
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
From the code you posted (without any exception details), I would guess that the problem is that _userManager is null.
However, you'll run into another problem if you fix that. Specifically, you should be using await instead of Result; the latter can cause deadlocks.
I had to call the .Wait() function manually, and then I can access the .Result successfully. In addition, my HttpContext was null so I had to use it inside of Index() like
public IActionResult Index()
{
DoSomethingWith(HttpContext);
return View();
}
and
System.Threading.Tasks.Task<ApplicationUser> user = GetApplicationUser(context);
user.Wait();
var user2 = user.Result;
I'm trying to make a delete function in my application that the user should be able to delete a product from the table but when the user presses the delete button, the error message "InvalidOperationException: Cannot remove an entity that has not been attached" comes up. I can't figure out what the problem is because it get's the product the user want's to delete(and displays it in the view) but when it get's to the HttpPost method, (when the user confirms that he want's to delete this product by pressing the delete button), the error message comes up... All the other methods work(create,edit,list...)only the delete method doesn't. I would really appreciate if someone can help me with this.
this is my code:
[HttpGet]
public ActionResult Delete(int id)
{
var p= prodRepo.GetProductById(id);
return View(p);
}
[HttpPost]
public ActionResult Delete(Product product)
{
prodRepo.DeleteProduct(product);
return RedirectToAction("Index");
}
this is the code from the productRepository class...
public Product DeleteProduct(Product product)
{
db = new NorthwindDataContext();
db.Products.DeleteOnSubmit(product);
db.SubmitChanges();
return product;
}
public Product GetProductById(int id)
{
db = new NorthwindDataContext();
var prod = (from p in db.Products
where p.ProductID==id
select p).Single();
return prod;
}
Just pass the id of product in delete action
[HttpPost]
public ActionResult DeleteConfirmed(int id)
{
Product_Table Ptobj = db.Product_Table.find(id);
db.Product_Table.remove(Ptobj);
db.savechanges()
}
I am able to get the User.Identity.Name value from Login Controller after redirect to Dashboard(another Controller) i am not able to receive the User.Identity.Name value (i am getting Null value)
below is my code:-
[HttpPost]
public async Task<ActionResult> SignInCallback()
{
var token = Request.Form["id_token"];
var state = Request.Form["state"];
var claims = await ValidateIdentityTokenAsync(token, state);
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
string Id = System.Web.HttpContext.Current.User.Identity.Name;
return Redirect("/Dashboard");
}
After return Redirect("/Dashboard"); Getting null value in Dashbord Controller.
Below is my Dashborad controller code :-
public ActionResult Index()
{
string Id = System.Web.HttpContext.Current.User.Identity.Name;
return View();
}
thank you for your reply,
i added BeginExecuteCore in base controller like this
`public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//string email = string.Empty;
dbEntities dbcontext = new dbEntities();
var userRoleName = (from n in dbcontext.VAgentClientEmails where n.Email == User.Identity.Name select n.Role).FirstOrDefault();
if (userRoleName == "SuperAdmin")
RouteData.Values["role"] = userRoleName;
else
RouteData.Values["role"] = "";
return base.BeginExecuteCore(callback, state);
}`
and i have given in home controller like this
[Route("~/{role}/SavedSearch/Index")]
public ActionResult Index()
{
...
}
its working for admin/savedsearch/index
and also if i give fjsdfk/savedsearch/index its working
in the above case it should not work..
and in else case i dont want role
do i need to do any changes?
How can I attach an existing View to an Action?
I mean, I've already attached this very View to an Action, but what I want is to attach to a second Action.
Example:
I've an Action named Index and a View, same name, attached to it, right click, add view..., but now, how to attach to a second one? Suppose an Action called Index2, how to achieve this?
Here's the code:
//this Action has Index View attached
public ActionResult Index(int? EntryId)
{
Entry entry = Entry.GetNext(EntryId);
return View(entry);
}
//I want this view Attached to the Index view...
[HttpPost]
public ActionResult Rewind(Entry entry)//...so the model will not be null
{
//Code here
return View(entry);
}
I googled it and cant find an proper answer...
It's possible?
you cannot "attach" actions to views but you can define what view you want be returned by an action method by using Controller.View Method
public ActionResult MyView() {
return View(); //this will return MyView.cshtml
}
public ActionResult TestJsonContent() {
return View("anotherView");
}
http://msdn.microsoft.com/en-us/library/dd460331%28v=vs.98%29.aspx
Does this help? You can use the overload of View to specify a different view:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
ViewBag.Message = "Hello I'm Mr. Index";
return View();
}
//
// GET: /Test/Index2
public ActionResult Index2()
{
ViewBag.Message = "Hello I'm not Mr. Index, but I get that a lot";
return View("Index");
}
}
Here is the View (Index.cshtml):
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>#ViewBag.Message</p>