when page load action result called twice in mvc - asp.net-mvc-4

when I load the page first hi action result and view and layout and again action result.
public ActionResult UploadPricedata()
{
oLoggedinUser = Session["LoginUser"] as List<Users>;
if (oLoggedinUser == null) return RedirectToAction("LogIn", "TransBankUsers");
return View();
}

Related

Redirecting to a response view with a model does not keep model properties

I have a form view that submits form data to the post action on a controler and then redirects to another view that uses logic to display either a success or failure, but the new view just shows blank values for model properties. Here is the post action:
[HttpPost]
public ActionResult ContactUs(TTT.Models.ContactUsModel model)
{
logger.Info(model.URL + "Contact Us Form submitted");
var userkey = model.ValidationKey;
var sessionkey = Session["ContactUsKey"];
var lastsubmission = Session["ContactUsTime"];
model.Response = "success";
//first check if honeypot was populated via a bot and if so send it to the success page without doing anything
if (model.WorkAddress != "")
{
logger.Info("honeypot triggered");
return View("ContactUsResponse", model);
}
I'll leave out the remainder of the controler, but
And here is the view it's redirecting to:
#using TTT.Models
#using Sitecore.Mvc
#model ContactUsModel
<h1>#Model.Title</h1>
<div>#Model.Body</div>
<div>
#if (#Model.Response == "fail")
{
#Model.Failure;
} else
{
#Model.Success;
}
</div>
Instead of returning a new view, call RedirectToAction and return new view from that controller.
[HttpPost]
public ActionResult ContactUs(TTT.Models.ContactUsModel model)
{
//--- Code omitted for brevity
if (model.WorkAddress != "")
{
logger.Info("honeypot triggered");
return RedirectToAction("ContactUsResponse", new { response = model });
}
}
public ActionResult ContactUsResponse(TTT.Models.ContactUsModel response)
{
return View(model)
}

Usage of UseStatusCodePagesWithReExecute with a message not working as expected

I'm using UseStatusCodePagesWithReExecute in my .NET Core 2.1 web app as follows
app.UseStatusCodePagesWithReExecute("/Error/{0}");
and in my Controller I point to 1 of 2 views, a 404.cshtml view and a generic error.cshtml view
public class ErrorController : Controller
{
[HttpGet("[controller]/{statusCode:int}")]
public IActionResult Error(int? statusCode = null)
{
if (statusCode.HasValue)
{
if (statusCode == (int)HttpStatusCode.NotFound)
{
return View(statusCode.ToString());
}
}
return View();
}
}
Now in my page controller I can do the following and it works as expected. It will show error.cshtml
public IActionResult SomePage()
{
return BadRequest();
}
Now if I change the above to the following, my ErrorController does get hit but by the time it does a blank view showing just "Some details" has been loaded in the browser.
public IActionResult SomePage()
{
return BadRequest("Some details");
}
Any ideas why? I want it to load error.cshtml
As #Kirk Larkin said , UseStatusCodePagesWithReExecute middleware won't work and it will only handle the status code .
You can use Result filters to write your custom logic to filter that and return a ViewResult :
public class StatusCodeResultFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// retrieve a typed controller, so we can reuse its data
if (context.Controller is Controller controller)
{
// intercept the NotFoundObjectResult
if (context.Result is BadRequestObjectResult badRequestObject)
{
// set the model, or other view data
controller.ViewData.Model = badRequestObject.Value;
// replace the result by a view result
context.Result = new ViewResult()
{
StatusCode = 400,
ViewName = "Views/Error/status400.cshtml",
ViewData = controller.ViewData,
TempData = controller.TempData,
};
}
}
await next();
}
}
Register the filter :
services.AddMvc(config =>
{
config.Filters.Add(new StatusCodeResultFilter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
In your view , you can directly get the detail message by :
#Model
Reference : https://stackoverflow.com/a/51800917/5751404

Redirect view to another if a certain condition is met

I'd like my Index controller to do 2 things based on the logged-in user's role:
If the user's role is "Master", then it should continue to load the Index view which contains a list of Companies registered on the website.
If the user's role is "Admin", then the View should redirect to the Edit view with the user's Company details preloaded into the view.
It's this second action that I'm having trouble with. Consider the following:
public ActionResult Index()
{
if (Session["userid"] != null)
{
if (String.Compare(Convert.ToString(Session["userrole"]), "Master", StringComparison.InvariantCultureIgnoreCase) == 0)
return View(db.Companies.ToList());
return View("Edit", new Id = Convert.ToInt32(Session["companyid"])) // this doesn't work
}
return RedirectToAction("Index", "Home");
}
How can I redirect the user to the other view and preload the required data?
Thanks in advance!
public ActionResult Index()
{
if (Session["userid"] != null)
{
if (String.Compare(Convert.ToString(Session["userrole"]), "Master", StringComparison.InvariantCultureIgnoreCase) == 0)
return View(db.Companies.ToList());
return RedirectToAction("Edit", new { id = Convert.ToInt32(Session["companyid"]});
}
return RedirectToAction("Index", "Home");
}
public ActionResult Edit(int id)
{
///Get your company by id here
}

how to call actionresult method in my controller from kendo grid in mvc4

I want to pass id to my actionresult method Delete
public ActionResult Delete(Guid AssetTypeId)
{
// _repo.DeleteAssetType(AssetTypeId);
if (_repo.DeleteAssetType(AssetTypeId) == 1)
{
return Index();
}
else
{
TempData["AlertMessage"] = "The DELETE statement conflicted with the REFERENCE constraint ";
return Index();
}
from kendo grid
.Action("Delete", "AssetType",new { AssetTypeId = "#=AssetTypeId#" }))
I guess you have AssetTypeId declared in your schema. In that case you don't need to send it separately. You just need to catch your Model in Delete. For deleting it should look like following; you can see details in their official demo site in here.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingPopup_Destroy([DataSourceRequest] DataSourceRequest request, ProductViewModel product)
{
if (product != null)
{
productService.Destroy(product);
}
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}

Preserving model in ASP.NET MVC 4

I have an ASP.NET MVC 4 app. I'm relatively new to ASP.NET MVC 4. Currently, I'm trying to build a basic Task list app.
public ActionResult Create()
{
var model = new TaskModel();
return View("~/Views/Task.cshtml", model);
}
[HttpPost]
public ActionResult Create(TaskModel model)
{
if (model.TaskName.Length == 0)
{
// Display error message
}
else
{
// Save to database
// Write success message
}
return View("~/Views/Task.cshtml", model);
}
If there is an error, I display an error message on the screen. My problem is, the previously entered values in the view are not shown. The entire view is blank.How do I preserve the values in the view in this case?
Thank you!
I use TempData for this.
public ActionResult Create()
{
var model = new TaskModel();
TempData["task"] = model;
return View("~/Views/Task.cshtml", model);
}
[HttpPost]
public ActionResult Create()
{
var task = (TaskModel)TempData["task"];
UpdateModel(task);
if (model.TaskName.Length == 0)
{
// Display error message
}
else
{
// Save to database
// Write success message
}
TempData["task"] = task;
return View("~/Views/Task.cshtml", model);
}
MVC works different than WebForms, since there is no concept of 'controls', you have to preserve the state yourself. Another option if you don't want to use TempData is to use an LosFormatter to Serialize your controls into a hidden HTML field. This would replicate the functionality of ViewState in ASP.NET WebForms