db.savechanges() line freezes in EF - asp.net-mvc

When the line db.savechanges() hits the breakpoint. Nothing happens. no errors in the catch block. The browser just freezes and data is not saved. I am using oracle with asp.net mvc. my code is given below;
public ResponseResult AddUserPermission(USER_PERMISSION permission)
{
try
{
_db.Entry(permission).State = EntityState.Modified;
_db.SaveChanges();
return new ResponseResult();
}
catch (Exception ex)
{
//return new ResponseResult();
return new ResponseResult(ResutlType.Error, ex.Message);
}
}
And the controller calls the method is given below:
[HttpPost]
[CustomAuthorize("Admin")]
public ActionResult Create(USER model)
{
try
{
string moduleId = Request.Form["ModuleId"];
string isSelected = Request.Form["IsSelected"];
model.DATE_CREATED = DateTime.Now;
model.DATE_UPDATED = DateTime.Now;
model.STATUS = (int)Status.Active;
var userPermission = processPermissionData(moduleId, isSelected);
//userPermission contains a list of permissions which i am trying to save
_userService.Add(model);
foreach (var permission in userPermission)
{
_userService.AddUserPermission(permission);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I get no response from the browser or VS 15. All i get is the loading sign in the browser tab.

Related

If no data in database then how to show "nodata" message in asp.net core

How to show No have any Data message in List view page if no have any record in the database.
This is my ICouponRepository interface to inject in this controller.
IEnumerable<ManuItem> GetAllManuItem();
This is my SQLManuItemRepository to inherit ICouponRepository
public IEnumerable<ManuItem> GetAllManuItem()
{
try
{
return context.ManuItems.Include(mi => mi.Category)
.Include(mi => mi.SubCategory)
.Where(mi => mi.IsDelete == false);
}
catch (Exception ex)
{
var exception = ex.Message;
return null;
}
}
This is my Controller method
public IActionResult Index()
{
try
{
var model = manuItemRepository.GetAllManuItem();
if (model == null)
{
ViewBag.NoData = "No have any Data";
return View();
}
return View(model);
}
catch (Exception ex)
{
ViewBag.Error = "Somthing was Worng" + ex.Message;
}
return View();
}
Any change in this method or change in View?
You can directly judge whether the returned model has data on the view. You can refer to the modified code below.
Controller
public IActionResult Index()
{
var model = new List<ManuItem>();
try
{
model = manuItemRepository.GetAllManuItem();
}
catch (Exception ex)
{
ViewBag.Error = "Somthing was Worng" + ex.Message;
}
return View(model);
}
View
#if (Model.Count() == 0)
{
<p>No have any Data</p>
}
else
{
<p>Have Data</p>
}

how should i send the validation error messages received from webapi(server) to the views in mvc6

[HttpPost]
public async Task<IActionResult> Add(CampaignModel model)
{
if (ModelState.IsValid)
{
var helper = new HttpClientHelper<CampaignModel>();
var response = await helper.PostAsync(UriHelper.POST_Campaigns_Add, model);
}
else
{
ModelState.AddModelError(string.Empty, "");
return View(model);
}
return RedirectToAction("List");
}
[HttpPost]
public async Task<IActionResult> InsertCampaigns([FromBody]CampaignDetailModel campaign)
{
if (ModelState.IsValid)
{
await _campaignService.InsertCampaign(campaign);
return new ObjectResult(campaign.Id);
}
return new BadRequestObjectResult(ModelState);
}
People have used HTTP response codes as a means to indicating what types of errors have occurred on the server. 200 OK would be success, whereas 401, 500, etc. could be used to indicate exception was thrown, the input was bad, etc.

How to call an ActionResult from another ActionResult in asp.net

I am creating a website for User registeration,display,login etc. I am currently trying to display the details of the user who have signed in. But within the actionResult of login I don't know how will i call the actionResult of display? I am new to asp.net. I need suggestions
public ActionResult login()
{
try
{
return View();
}
catch (Exception ex)
{
throw ex;
}
}
[HttpPost]
public ActionResult login(DEntities.Users user)
{
try
{
services.CheckUser(user);
controlsuccess = services.servicesuccess;
if (controlsuccess == true)
{
return RedirectToAction("display");
//return View("display");
}
else
{
return HttpNotFound();
}
}
catch (Exception ex)
{
throw ex;
}
}
public ActionResult display()
{
return View();
}
[HttpPost]
public ActionResult display(int id = 0)
{
try
{
DEntities.Users user = services.GetUserbyId(id);
return View(user);
}
catch (Exception ex)
{
throw ex;
}
}
Remove the [HttpPost] attribute from the display action.
If both actions are in the same controller, then just pass the action name:
return RedirectToAction("display", new { id = 1 });
Or if the actions are in different controllers, pass the action and controller names:
return RedirectToAction("display", "controllername", new { id = 1 });
Or if it is necessary to use [HttpPost], you can learn how to
RedirectToAction to a POST Action.

RavenDB with asp.net mvc Update Issue

I have a small project in asp.net mvc 3 and I am using RavenDB to store data.
But when i am trying to update entity i have error saying
"Attempted to associate a different object with id 'orders/257'"
I have a service class to menage entities.
This is method to update entity called Order.
I'v omitted the rest of methods baceuse of clarity
public ErrorState UpdateOrder(Order order)
{
try
{
documentSession.Store(order);
documentSession.SaveChanges();
return new ErrorState { Success = true };
}
catch (Exception ex)
{
return new ErrorState { Success = false, ExceptionMessage = ex.Message };
}
}
This is rest of OrderRepository
private readonly IDocumentSession documentSession;
public OrderRepository(IDocumentSession _documentSession)
{
documentSession = _documentSession;
}
ErrorState class is for menagege errors in app, it contains bool success and string message of exception.
This is my edit Actions.
public ActionResult Edit(int id)
{
Order order = orderRepository.ObtainOrder(id);
if (order == null)
{
TempData["message"] = string.Format("Order no: {0} not found", id);
return RedirectToAction("Index");
}
return View(order);
}
[HttpPost]
public ActionResult Edit(Order order)
{
if(!ModelState.IsValid)
return View();
errorState = orderRepository.UpdateOrder(order);
if (errorState.Success)
{
TempData["message"] = string.Format("Order no: {0} has been changed", order.Id);
return RedirectToAction("Index");
}
else
{
TempData["Message"] = string.Format("Error on update order no: {0} MSG: {1}", order.Id,errorState.ExceptionMessage);
return RedirectToAction("Index");
}
}
This is the rest of the controller , I'v omitted the rest of actions baceuse of clarity.
private readonly IOrderRepository orderRepository;
private ErrorState errorState;
public HomeController(IOrderRepository _orderRepository,IDocumentSession _documentSession)
{
orderRepository = _orderRepository;
}
You already have an instance of an order with that id.
Check the session lifetime, is it possible that you have the same session across requests?

How do I Redirect to another Action/Controller in MVC3 from a VOID method?

I have a controller method that returns a void because it is building an Excel report for the user to download. The Excel 3rd party library we're using is writing to the response itself. The method looks something like this:
[HttpGet]
public void GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
}
catch (Exception ex)
{
// This is wrong, of course, because I'm not returning an ActionResult
Response.RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
There are several security checks in place that throw exceptions if the user doesn't meet certain credentials for fetching the report. I want to redirect to a different page and pass along some information about the exception, but I can't figure out how to do this in MVC3....
Any ideas?
You could use the following code
Response.Redirect(Url.Action("Error", "Report", new { exceptionType = ex.GetType().Name }));
But have you taken a look at the FilePathResult or FileStreamResult ?
Instead of letting the 3rd part library write to the response directly get the content use regular ActionResult and return File(...) for the actual file or RedirectToAction(...) (or RedirectToRoute(...)) on error. If your 3rd party library can only write to Response you may need to use some tricks to capture it's output.
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
var content = excelReport.MakeReport(System.Web.HttpContext.Current.Response);
return File(content, "application/xls", "something.xls");
}
catch (Exception ex)
{
RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
You can return an EmptyActionResult:
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
return new EmptyResult();
}
catch (Exception ex)
{
return RedirectToAction("Error", "Report", rnew { exceptionType = ex.GetType().Name });
}
}
Not sure if it works, haven't tested it.
Another approach would be using an exception filter:
public class MyExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var routeValues = new RouteValueDictionary()
{
{ "controller", "Error" },
{ "action", "Report" }
};
filterContext.Result = new RedirectToRouteResult(routeValues);
filterContext.ExceptionHandled = true;
// Or I can skip the redirection and render a whole new view
//filterContext.Result = new ViewResult()
//{
// ViewName = "Error"
// //..
//};
}
}

Resources