Redirect to an action from a class - asp.net-mvc-3

I have been researching this and no luck. Is it possible to redirectToAction from a class. I moved my code from my controller to a class because it was too long. I will like to redirectToAction and user this method in my controller.
return RedirectToAction("CreateReportFile", "Home", new { result = strObj.ToString() });

RedirectToAction is a method on your controller, so you'd need to pass the controller instance to your class:
public ActionResult Foo()
{
var myClass = new MyClass(this);
return myClass.Bar();
}
I wouldn't call that good code though. You could instead act on the return value from the method in your class:
public ActionResult Foo()
{
var myClass = new MyClass();
var result = myClass.Bar();
if (result == "baz") // bool, Enum, whatever you like
{
return RedirectToAction(
"CreateReportFile",
"Home",
new { result = myClass.StrObj.ToString() }
);
}
else
{
//
}
}

Related

Object State validation based on Controller Actions in ASP.NET Core MVC

I'm trying to implement a DRY based validation using IValidatableObject in an ASP.NET Core 3.1 MVC application. I'm using both data annotations to validate "format" rules, and Validate(ValidationContext validationContext) method to implement my business rules.
So far, it's working smoothly, now, I have some extra business rules based on Object State, which will control some kind of workflow of my Objects, and that workflow will depend on the controller action to be executed.
I want to avoid adding business rules in my controller and want to centralize any validation within my Model. I'm wondering if there's any standard way to do it, otherwise I'll implement my own mechanism.
For example:
Trying to Delete MyObject with STATUS_1 should give a validation error...
This is MyObject class:
public class MyObject : IValidatableObject
{
public MyObjectState State { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "decimal(18, 2)")]
public decimal Value{ get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//My custom model validation here
}
public IEnumerable<ValidationResult> ValidateState(ActionExecutedContext actionContext)
{
var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor.ActionName == "Delete" && State != MyObjectState.STATE_1)
yield return new ValidationResult("You cannot delete if STATE_1");
}
}
These may be the possible MyObject statuses:
public enum MyObjectState
{
STATE_1 = 1,
STATE_2 = 2,
STATE_3 = 3
}
This may be MyObject Controller with Delete Action:
public class MyObjectController: Controller
{
private readonly ApplicationDbContext _context;
public MyObjectController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var myObject = await _context.MyObject.FindAsync(id);
var validationStateResult = myObject.ValidateState(null);
//Not sure how to provide the action context here
if (!validationStateResult)
{
return RedirectToAction(nameof(Index)).WithWarning("ALERT: ", validationStateResult.ToString());
}
return View(myObject);
}
}
You can use ajax in view,action return errormessage or MyObject to ajax,and ajax will alert errormessage or redirect to delete Page.In controller,you can get actionName to check.Here is a demo worked:
MyObject ValidateState(I change the ActionName to DeleteCheck,and you can use ActionName to check ):
public IEnumerable<ValidationResult> ValidateState(string ActionName)
{
if (ActionName == "DeleteCheck" && State == MyObjectState.STATE_1)
yield return new ValidationResult("You cannot delete if STATE_1");
}
MyObjectsController(You can get actionName with RouteData.Values["action"]):
public async Task<IActionResult> DeleteCheck(int? id)
{
if (id == null)
{
return NotFound();
}
var myObject = await _context.MyObjects.FindAsync(id);
var action =(string)RouteData.Values["action"];
var validationStateResult = myObject.ValidateState(action);
string messages = string.Join("", myObject.ValidateState(action)
.SelectMany(x => x.ErrorMessage));
TempData["Message"] = messages;
if (messages!=null&&messages != "")
{
return Json(messages);
}
return Json(myObject);
}
public IActionResult Delete(MyObject myObject) {
return View(myObject);
}
View:
<a href="#" onclick="delete1(#item.Id)" >Delete</a>
function delete1(id) {
$.ajax({
method: 'get',
url: "MyObjects/DeleteCheck?Id=" + id,
dataType: "json",
success: function (data) {
if (typeof data === 'object') {
window.location.href = "/MyObjects/Delete?Id=" + data.id + "&&State=" + data.state + "&&Price=" + data.price;
//alert("object");
} else {
alert(data)
}
}
});
}
result:

How do I return specific string value from webapi?

I want to return following JSON, but I missed the syntax. How can I correct it?
In my HomeController.cs,
If (result.IsUserActive) return JSON { “UserStatus” : “Active” }
How can I return value “UserStatus” : “Active” In Get method of webapi?
It must be like something:
[HttpGet]
public IHttpActionResult GetUserStatus(int id)
{
var result = GetStatus(id);
if (result.IsUserActive)
{
return json ({ “UserStatus” : “Active” });
}
You can simply return the Json like:
var result = new {UserStatus="Active" };
return Ok(result);

IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet) ISSUE

IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet); method is changed and not allowing to set JsonrequestBehavior. What is alternative in MVC6
That overload of Json method which takes JsonRequestBehavior does not exist in the aspnet core any more.
You can simply call the Json method with the object data you want to send back.
public IActionResult GetJsonData()
{
var rows = new List<string> { "Item 1","Item 2" };
return Json(rows);
}
Or even
public IList<string> GetJsonData()
{
var rows = new List<string> {"aa", "bb" };
return rows;
}
or using Ok method and having IActionResult as the return type.
public IActionResult GetJsonData()
{
var rows = new List<string> { "aa", "bb" };
return Ok(rows);
}
and let the content negotiator return the data in the requested format(via Accept header). The default format used by ASP.NET Core MVC is JSON. So if you are not explicitly requesting another format(ex :application/xml), you will get json response.
Try this
[HttpGet]
public JsonResult List()
{
var settings = new JsonSerializerSettings();
return Json(rows, settings);
}
Try this
public JsonResult GetJsonData()
{
var data= //your list values
return Json(data);
}
JsonRequestBehavior is deprecated from ASP.net core 1. Just use return Json();

How to convert LINQ result to JSON and pass it to View in MVC3

In my controller i have the following code
public ActionResult
{
var roomdetails = db.RoomDetails.Include(r => r.RoomType).Include(r => r.FloorNames);
roomdetails = roomdetails.OrderByDescending(s => s.FloorNames.FloorName);
return View(roomdetails.ToList());
}
But i want to send the roomdetails as json object so that i can use jquery to catch the request and do further dynamic processing in my View.So how to convert roomdetails to json object.Please help me...
Note: Use Newtonsoft.Json.dll version 8.0.2
return an instance of this class to your controller method.
public class ActionResult_Json : System.Web.Mvc.ActionResult
{
public object To_Serialize_Object { get; set; }
public ActionResult_Json(object To_Serialize_Object)
{
this.To_Serialize_Object = To_Serialize_Object;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/json";
//serialize object to string
string Serialized_Object_String = Newtonsoft.Json.JsonConvert.SerializeObject(To_Serialize_Object, new Newtonsoft.Json.JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
});
//write json to response stream
context.HttpContext.Response.Write(Serialized_Object_String);
}
}
Just return a JsonResult:
public JsonResult Index()
{
var roomdetails = db.RoomDetails.Include(r => r.RoomType).Include(r => r.FloorNames)
.OrderByDescending(s => s.FloorNames.FloorName);
return Json(roomdetails.ToList(), JsonRequestBehavior.AllowGet);
}
You would need your jquery to process the json in the way that you want and display what you want. Typically this works well if it's called from your view via ajax.
#{
ViewBag.Title = "Index";
}
Reception
$(document).ready(function () {
$.getJSON('/Reception/Index1', function (data) {
console.log(data);
if (data.success) {
alert("hai");
//ShowStockQuote(data);
}
else {
alert("faliure");
}
});
});
#Html.ActionLink("Create New", "Create")
You may try this.
public JsonResult Index()
{
var roomdetails = db.RoomDetails.Include(r => r.RoomType).Include(r => r.FloorNames);
roomdetails = roomdetails.OrderByDescending(s => s.FloorNames.FloorName);
return Json(roomdetails.ToArray(), JsonRequestBehavior.AllowGet);
}

Returning Multiple partial views from single Controller action?

I need to update Multiple from an Ajax call , I am confused as in how to return these Multiple views from the Controller Action method.
You can only return one value from a function so you can't return multiple partials from one action method.
If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel.
E.g.
Your view model would look like:
public class ChartAndListViewModel
{
public List<ChartItem> ChartItems {get; set;};
public List<ListItem> ListItems {get; set;};
}
Then your controller action would be:
public ActionResult ChartList()
{
var model = new ChartAndListViewModel();
model.ChartItems = _db.getChartItems();
model.ListItems = _db.getListItems();
return View(model);
}
And finally your view would be:
#model Application.ViewModels.ChartAndListViewModel
<h2>Blah</h2>
#Html.RenderPartial("ChartPartialName", model.ChartItems);
#Html.RenderPartial("ListPartialName", model.ListItems);
There is a very good example here....
http://rhamesconsulting.com/2014/10/27/mvc-updating-multiple-partial-views-from-a-single-ajax-action/
Create a helper method to package up the partial view...
public static string RenderRazorViewToString(ControllerContext controllerContext,
string viewName, object model)
{
controllerContext.Controller.ViewData.Model = model;
using (var stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var viewContext = new ViewContext(controllerContext, viewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
Create a controller action to bundle the multiple partial views....
[HttpPost]
public JsonResult GetResults(int someExampleInput)
{
MyResultsModel model = CalculateOutputData(someExampleInput);
var totalValuesPartialView = RenderRazorViewToString(this.ControllerContext, "_TotalValues", model.TotalValuesModel);
var summaryValuesPartialView = RenderRazorViewToString(this.ControllerContext, "_SummaryValues", model.SummaryValuesModel);
return Json(new { totalValuesPartialView, summaryValuesPartialView });
}
Each partial view can use its own model if required or can be bundled into the same model as in this example.
Then use an AJAX call to update all the sections in one go:
$('#getResults').on('click', function () {
$.ajax({
type: 'POST',
url: "/MyController/GetResults",
dataType: 'json',
data: {
someExampleInput: 10
},
success: function (result) {
if (result != null) {
$("#totalValuesPartialView").html(result.totalValuesPartialView);
$("#summaryValuesPartialView").html(result.summaryValuesPartialView);
} else {
alert('Error getting data.');
}
},
error: function () {
alert('Error getting data.');
}
});
});
If you want to use this method for a GET request, you need to remove the [HttpPost] decorator and add JsonRequestBehavior.AllowGet to the returned JsonResult:
return Json(new { totalValuesPartialView, summaryValuesPartialView }, JsonRequestBehavior.AllowGet);
Maybe this solution can help you:
http://www.codeproject.com/Tips/712187/Returning-More-Views-in-an-ASP-NET-MVC-Action

Resources