ActionResult Create with conditions - c#

im doing an MVC with CRUDS.
this is my code.
[HttpPost]
public ActionResult Create([Bind(Include = "FileStatusID, Name, MinValue, MaxValue")] fileStatusModel FILeStatusModel, TBL_FileStatus tBL_FileStatus) //include tem os valores que vamos inserir na view
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
if (ModelState.IsValid)
{
TBL_FileStatus item = new TBL_FileStatus()
{
Name = FILeStatusModel.Name,
MinValue = FILeStatusModel.MinValue,
MaxValue = FILeStatusModel.MaxValue,
Ative = true,
CreateDate = DateTime.Now,
CreateBy = userID
};
db.TBL_FileStatus.Add(item);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I want to create a status with special conditions.
I have a table with ID, status, minvalue and maxvalue and have an interval of numbers in those values.
I want to create another status out of the range of those numbers.
ex: minvalue: 20 maxvalue: 40
So.. When i create a new status, if i put numbers inside that range, its say a message like "already exist in that range", if not, it creats de status.
thanks

1. Rendering layout page from ActionResult (using Controller. View extension method)
The Controller. View method has two extension methods, using these
extension methods we can pass a master page (layout page) name and
render a layout page based on a condition.
Example Code
public ActionResult About()
{
return View("About","_otherLayout");
}
public ActionResult OtherAbout()
{
string myName = "Jignesh Trivedi";
return View("About", "_otherLayout", myName);
}
2. Using _ViewStart.cshtml Page
The Controller. View method has two extension methods, using these
extension methods we can pass a master page (layout page) name and
render a layout page based on a condition.
Using the _ViewStart.cshtml page, we can change the layout page based
on a condition.
Example Code
#{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string layout = "";
if (controller != "Home")
{
layout = "~/Views/Shared/_otherLayout.cshtml";
}
else
{
layout = "~/Views/Shared/_Layout.cshtml";
}
Layout = layout;
}
We can also create multiple _ViewStart.cshtml pages. The file
execution is dependent upon the location of the file within the folder
hierarchy and the view being rendered. The MVC Runtime will first
execute the code of the _ViewStart.cshtml file located in the root of
the Views folder.
3. Define the Layout page in each view
We can override the default layout rendering by setting the Layout
property of the View using the following code.
#{
Layout = "~/Views/Shared/_otherLayout.cshtml";
ViewBag.Title = "About Us";
}
As presented in the article by : Jignesh Trivedi at
https://www.c-sharpcorner.com/UploadFile/ff2f08/rendering-layouts-base-on-condition-in-Asp-Net-mvc/

Related

When using Abp Modal tag helper with widget at the same time, the js file bind to widget cannot be loaded

In my project, i need to create an reusable "food select list" component, this component will use as food index page and food select modal window.
I created a FoodsViewComponent which inherit from AbpViewComponent and also marked as 'Widget', below are the code of this component:
[Widget(
StyleFiles = new[] { "/Pages/Shared/Components/FoodList/Default.css" },
ScriptTypes = new[] { typeof(FoodListWidgetScriptBundleContributor) },
RefreshUrl = "Widget/LoadFoodListComponent"
)]
[ViewComponent(Name = "FoodList")]
public class FoodsViewComponent : AbpViewComponent
{
private readonly IFoodAppService _foodAppService;
public FoodsViewComponent(IFoodAppService foodAppService)
{
_foodAppService = foodAppService;
}
public async Task<IViewComponentResult> InvokeAsync(
string keyword,
FoodSelectMode mode = FoodSelectMode.List,
string onclick = null,
string foodSelect = null,
string processSelect = null,
int page = 1,
int pageSize = 2)
{
PagedKeywordSearchRequestInputDto input = new()
{
Keyword = keyword,
MaxResultCount = pageSize,
SkipCount = (page - 1) * pageSize
};
PagedResultDto<FoodBaseDto> results = await _foodAppService.GetPagedListAsync(input);
ViewBag.Keyword = keyword;
ViewBag.Page = page;
ViewBag.PageSize = pageSize;
ViewBag.FoodSelectMode = mode;
ViewBag.FoodSelect = foodSelect;
ViewBag.Onclick = onclick;
ViewBag.ProcessSelect = processSelect;
return View(results);
}
}
And the FoodListWidgetScriptBundleContributor code as below:
public class FoodListWidgetScriptBundleContributor : BundleContributor
{
public override void ConfigureBundle(BundleConfigurationContext context)
{
context.Files
.AddIfNotContains(new string[]
{
"/Pages/Shared/Components/FoodList/Default.js" ,
"/libs/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"
});
}
}
The razor page of this component is as below:
#using Chriswu00.HealthEngine.FoodNutrition.Web;
#model PagedResultDto<FoodBaseDto>
#{
int p = ViewBag.Page;
int pageSize = ViewBag.PageSize;
string keyword = ViewBag.Keyword;
FoodSelectMode mode = ViewBag.FoodSelectMode;
string foodSelect = ViewBag.FoodSelect;
string componentId = $"foodsWidget_{mode}";
string onclick = ViewBag.Onclick;
string processSelect = ViewBag.ProcessSelect;
}
<div id="#componentId">
#foreach (var food in Model.Items)
{
<food-card food-id="#food.Id"
food-name="#food.Name"
food-click="#onclick"
food-select-mode="#mode"
food-select="#foodSelect"></food-card>
}
<boot-paginator link-url="/Widget/LoadFoodListComponent?keyword=#keyword&mode=#mode&foodSelect=#foodSelect&processSelect=#processSelect"
page="#p"
page-size="#pageSize"
total-items="#Model.TotalCount">
<ajax-options update-target-id="#componentId"
on-begin=""
on-complete="">
</ajax-options>
</boot-paginator>
#if (mode == FoodSelectMode.MultipleSelect ||
mode == FoodSelectMode.SingleSelect)
{
<abp-button button-type="Primary" onclick="#processSelect">Process Select</abp-button>
}
</div>
'food-card' is the custom html tag helper i created for display food item and the 'boot-paginator' is the custom html tag helper i created for pagination which has the ability to load and refresh 'the next page' by ajax.
Those component works fine, until i made a 'Modal Page' as 'Food selector'.
The Scenario is: My project is a Food and Nutrition database, user can create food and the system provids the api for getting the nutrition info of those foods. I defined two different types of food, one is just called 'Food' and the other is called 'Composite Food'. As the name suggests,the 'Composite Food' is the combination of more than one food, so during the food creation process, user can select multiple existing foods as the 'food facts' for the new food.
So i want to use a bootstrap modal window with a 'paginated food list' as the food fact selection UI, which i can integrate to the composite food creation and update pages.
I follow the 'Modals' chapter from the abp official docs (https://docs.abp.io/en/abp/6.0/UI/AspNetCore/Tag-Helpers/Modals) and create a 'FoodListModal' razor page as below:
#page
#using Microsoft.AspNetCore.Mvc.Localization
#using Chriswu00.HealthEngine.FoodNutrition.Localization;
#using Chriswu00.HealthEngine.FoodNutrition.Web.Pages.Foods;
#model Chriswu00.HealthEngine.FoodNutrition.Web.Pages.Foods.FoodListModalModel
#inject IHtmlLocalizer<FoodNutritionResource> Localizer
#{
Layout = null;
}
<abp-modal>
<abp-modal-header title="#Localizer[$"Food{Model.FoodSelectMode}"].Value"></abp-modal-header>
<abp-modal-body>
#await Component.InvokeAsync("FoodList", new
{
mode = Model.FoodSelectMode,
onclick = Model.Onclick,
foodSelect = Model.FoodSelect,
pageSize = 10,
processSelect = Model.ProcessSelect
})
</abp-modal-body>
</abp-modal>
After i integrate this modal to the composite food creation page, everything works fine except the pagination, instead of refresh within the food list, it reload the whole page. I guessed it is the problem of loading the jquery.unobtrusive-ajax.js. Because the 'Food List component' contains two js files, Default.js and the jquery.unobtrusive-ajax.js, To confirm that my guess was correct, i added an alert command into Default.js. After i tested, the Food Index page which also integrated the Food List component works fine and shows the alert when click on the pagination. But the 'Food Selector Modal' didn't shows the alert and reload the whole page.
That's what I'm currently investigating. Is this a bug of the framework? Or am I missing some knowledge point?

give access to visibility a web tab to a group of people, get data from database to Layout page | Asp.Net Core 3.1

Desc:
I have a web tab and I need to give access to visibility
to a group of people from the database
I tried:
I am downloading a list of people for whom the bookmark must be covered
for. exp. single login: AD/ABCD
I try to send them to a partial view
and load this partial view into the layout by #Html.Action
Controller:
using ActionExecutingContext = Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext;
using ActionResult = Microsoft.AspNetCore.Mvc.ActionResult;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
public class PrivilegeController : Controller
{
private readonly MembersDbContext _membersContext;
public PrivilegeController(MemebersDbContext membersDbContext)
{
_membersContext= membersContext;
}
[ChildActionOnly]
public ActionResult Header(string section)
{
var listOfManagers = _membersContext. Members.Select(x => x.Adlogin).Distinct().ToList();
ViewData["listManager"] = listOfManagers;
return PartialView("_toDevLayout");
}
}
PartialView: _toDevLayout
Layout: _TrueLayout
#Html.Action("Header", "Privilege")
what is wrong?
I got an error in my project that html.action does not exist (version mvc / core 3.1 too high)
I need to find a different solution
Cannot resolve symbol 'Action'
Hi use this in your layout page directly and use list of managers as required.
enter code here-> #{var listOfManagers = _membersContext. Members.Select(x => x.Adlogin).Distinct().ToList();}

Pagination in jquery data table destroy partial view

I have table that contains data and links that open partial view with related data. I use jquery datatable, when I'm on first page everything works fine, but if I go to the next pages and cliked link I dont have beauty partial view, page return only source code from partial view file and skips _Layout.cshtml.
What should I do to make the code work correctly?
Controller:
public ActionResult KsiazkiZlecenia(int zlecKompletID, string magazynID)
{
SystemMagazynowy ksiazki = new SystemMagazynowy();
var listaksiazek = ksiazki.PobierzInfoKsiazek(zlecKompletID, magazynID);
ViewBag.ksiazki = listaksiazek;
return PartialView();
}
Link:
#Html.ActionLink("Książki", "KsiazkiZlecenia", new { zlecKompletID = item.ZlecKompletID, magazynID = ViewBag.MagazynID }, new { #data_modal = "" })

C# ASP.NET MVC Passing data to GridView from DataTable

I want to do the menu page in a MVC project, there I need to populate some GridViews with different data from some models. First I created some datasets which contain the datatables; in the controller i call the index view which shows the main page.
public ActionResult Index()
{
..........
return View();
}
Index view
#{ Layout = "~/Views/Shared/_mainLayout.cshtml"; }
#{Html.RenderPartial("TicketsPartial");}
#Html.DevExpress().PageControl(s =>
{
s.Name = "tabcontrol";
s.TabPages.Add(tabPage =>
{
tabPage.Text = "Inbox";
tabPage.SetContent(() =>
{
Html.RenderPartial("InboxPartial");
});
});
s.TabPages.Add(tabPage =>
{
tabPage.Text = "Sent";
tabPage.SetContent(() =>
{
Html.RenderPartial("SentPartial");
});
});
}).GetHtml()
So I'm trying to use the Html.RenderPartial to call some partial views... here's the code in InboxPartial
#model DataModels.Email.DS_EmailMessages.DT_com_mail_messagesDataTable
#Html.DevExpress().GridView(s =>
{
s.Name = "Inbox";
s.KeyFieldName = "idticket";
s.Width = System.Web.UI.WebControls.Unit.Percentage(100);
}).Bind(Model).GetHtml()
So first I give the model to the view... the datatable from which the data should be loaded and I bind it to the gridview...
The thing is that this isn't displaying any data and also any column...and I really can't understand why... for example if I give the datatabel as a parameter in the controller like this:
public ActionResult Index()
{
..........
return View(dS_Tickets.DT_com_consultant_tickets);
}
And i erase the model from the views so there will not be any conflict, each partialview will show the columns and data taken from the datatabel, but only from that one table that I gave as a parameter.. I need to take the data from different tables... how can I do this?
Note: I'm using an extension called DevExpress v.12

Output current html view to string when button clicked

I have a print-ready view that renders nicely in the browser. It would be nice to offer users the option to click a link or button located on that view that would call an action to create a PDF from the raw HTML in the view. I have the PDF processing part figured out, I just need help figuring out:
When link or button is clicked, put the rendered HTML from that view into a string variable to be sent to my PDF processing code.
Here is my Controller method that renders the page:
public ActionResult ViewReport(int? id, string memberID, int month, int year)
{
var task = new ViewReportTask();
return View(task.BuildViewModel(id, memberID, month, year));
}
The view is just a lot of html and razor code blocks so I did not include it here.
Thanks
I'm using following approach:
You have Action method which generates your View:
public ActionResult ViewReport(int? id, string memberID, int month, int year)
{
var task = new ViewReportTask();
return View(task.BuildViewModel(id, memberID, month, year));
}
Create one more ActionResult:
public ActionResult PrintMyView(int? id, string memberID, int month, int year)
{
return new ActionAsPdf( "ViewReport", new { id= id; memberID=memberID; month=month; year=year})
{ FileName = "ViewReport.pdf"};
}
To have ActionAsPdf method you need to install Rotativa Nuget Package:
Install-Package Rotativa
Now to save your page as pdf user must click on following link on your view:
#Html.ActionLink("Save as PDF, "PrintMyView", "Home", new{id= id, memberID=memberID, month=month, year=year}, null)
//** I can't see where you takes parameters in your view, so I just list them.
It works fine for me.

Categories