Pass parameter form MVC to Stimulsoft report - asp.net

The View code is as follows:
#using Stimulsoft.Report.Mvc;
#using Stimulsoft.Report;
#{
ViewBag.Title = "ListPouyaProject";
Layout = "~/Views/Shared/_mainView.cshtml";
}
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-body">
<div class="form-group">
Start Date: <input type="text" id="date1" name="date1" onclick="PersianDatePicker.Show(this, '1392/03/22');" />
End Date : <input type="text" id="date2" name="date2" onclick="PersianDatePicker.Show(this, '1397/03/22');" />
</div>
<div class="form-group">
#Html.Stimulsoft().StiMvcViewer(new StiMvcViewerOptions()
{
Actions =
{
GetReport = "Report4_ListPouyaProject",
ViewerEvent = "ViewerEvent"
}
})
</div>
</div>
</div>
</section>
The Controller code is as follows:
public ActionResult Report4_ListPouyaProject()
{
var report = new StiReport();
report.Load(Server.MapPath("~/Content/Reports/ListPouyaProject.mrt"));
return StiMvcViewer.GetReportResult(report);
}
public ActionResult ListPouyaProject()
{
return View();
}
public ActionResult ViewerEvent()
{
return StiMvcViewer.ViewerEventResult();
}
I want to pass the date1 and date2 variables to the controller from view.
To do this, we need to add the following commands to the contoroller :
report.CompiledReport.DataSources["spm_report_4_ListPouyaProject"].Parameters["StartDate"].ParameterValue = DateTime.Parse(date1);
report.CompiledReport.DataSources["spm_report_4_ListPouyaProject"].Parameters["EndDate"].ParameterValue = DateTime.Parse(date2);
How to pass the parameters date1 and date2 from view to controller?

First, you need to add the StiMvcViewer component to the view page. Also, you need to pass the StiMvcViewerOptions object to the constructor. The minimum required options are two actions - GetReport and ViewerEvent, they are located in the Actions options group.
#using Stimulsoft.Report.MVC;
#Html.Stimulsoft().StiMvcViewer(new StiMvcViewerOptions()
{
Actions =
{
GetReport = "GetReport",
ViewerEvent = "ViewerEvent"
}
})
<div style="width: 150px;">
#Html.ActionLink("Simple List", "Index", new { id = "1" })
<br />Report Snapshot
</div>
and in controoller :
public ActionResult GetReport(int? id)
{
// Create the report object
StiReport report = new StiReport();
switch (id)
{
// Load report snapshot
case 1:
// Load report
// Load report snapshot
report.LoadDocument(Server.MapPath("~/Content/Reports/SimpleList.mdc"));
break;
}
// Load data from XML file for report template
if (!report.IsDocument)
{
DataSet data = new DataSet("Demo");
data.ReadXml(Server.MapPath("~/Content/Data/Demo.xml"));
report.RegData(data);
}
return StiMvcViewer.GetReportResult(report);
}
public ActionResult ViewerEvent()
{
return StiMvcViewer.ViewerEventResult();
}

Related

asp.net core - form values return null

Passing department and title models for use data in selectbox and passing employee model for save data from user. tring to pass values from partial view but in controller values return null.
partial view:
#model (List<Department> Departments, List<Title> Titles, Employee e)
<form class="g-3" asp-action="CreateEmployee" asp-controller="Employees" method="post">
<div class="row">
<div class="col-lg-6">
<div class="mb-3">
<label for="Name" class="form-label">İsim</label>
<input asp-for="e.Name" type="text" class="form-control" id="Name">
<div class="invalid-feedback">
İsim alanı boş bırakılamaz.
</div>
</div>
</div>
</div>
<button type="submit">Tek Form</button>
</form>
controller:
public IActionResult CreateEmployee()
{
HR_ManagementContext context = new HR_ManagementContext();
var departments = context.Departments.ToList();
var titles = context.Titles.ToList();
var models = (departments, titles, new Employee());
return View(models);
}
[HttpPost]
public IActionResult CreateEmployee(Employee employee)
{
return RedirectToAction("CreateEmployee");
}
Set the name attribute in the input tag:
<input asp-for="e.Name" type="text" class="form-control" id="Name", name="employee.Name">
The second solution is to use model name item3 generated by the MVC:
[HttpPost]
public IActionResult CreateEmployee(Employee item3)
{
return RedirectToAction("CreateEmployee");
}
Thx #Jackdaw his answer also working too.
I found an alternative
in Controller you can bind model:
public IActionResult CreateEmployee([Bind(Prefix = "Item3")]Employee employee)
{
return RedirectToAction("CreateEmployee");
}
Item3 is the prefix of tuple model.
#model (List<Department> Departments, List<Title> Titles, Employee e)
Department = Item1
Titles = Item2
Employee = Item3

Model is null in view on foreach

I have added a list to my view model but when I access it in a foreach loop in the view it throws:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_MyActivationCampaign_Campaign.ExecuteAsync() in Campaign.cshtml
+ foreach(var dp in Model.DpRestrictedList)
This is the list I have added:
public List<DpRestricted> DpRestrictedList { get; set; } = new List<DpRestricted>()
{
new DpRestricted(){DpId = 1, Name = "Post Restricted" },
new DpRestricted(){DpId = 2, Name = "Unrestricted" },
new DpRestricted(){DpId = 3, Name = "Customer Restricted" }
};
}
public class DpRestricted
{
public int DpId { get; set; }
public string Name { get; set; }
}
and I am trying to loop over it like this:
<div class="row">
<fieldset>
<legend>Delivery Methods</legend>
<div id="radio">
#*<input type="radio" id="new-method">
<label for="new-method">New Method</label>
<input type="radio" id="dm-101" checked="checked">
<label for="dm-101">DM_101</label>
<input type="radio" id="delivery-method-2">
<label for="delivery-method-2">Delivery Method 2</label>*#
#{
foreach(var dp in Model.DpRestrictedList)
{
#Html.RadioButtonFor(model => model.DeliveryPointRestrictionId, dp);
}
}
</div>
</fieldset>
</div>
Using statement and example:
#model WorkstreamX.Web.Core.ViewModels.ActivationCampaignViewModel
...
<div class="col-md-4">
<label for="headline">Campaign</label>
#Html.EditorFor(model => model.CampaignName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CampaignName)
</div>
The above is the using statement in the view and an example of how it is already being used elsewhere in it. When I check it is not just the list that is null but the Model in the loop statement is also null. Is it a case of me needing to new up the view model in the controller at this point? That is what I am about to try I just wanted to state this question and maybe find out why this is happening. Any advice here greatly appreciated.
[edit] How I fixed this issue:
I added an argument to my view:
before return View();
after return View(new ActivationCampaignViewModel());
I still don't quite understand the why of this as I appeared to have a model before. I am assuming that because I didn't call the constructor the list wasn't constructed and made it all fall over.
Your code should be like the below one.
Public ActionResult GetEmployee()
{
var employee = GetEmployee();
return View(employee);
}
#model IEnumerable<Appname.ViewModel.Employee>
#{
foreach(var data in Model) {}
}
How I fixed this issue:
I added an argument to my view:
before return View();
after return View(new ActivationCampaignViewModel());
I still don't quite understand the why of this as I appeared to have a model before. I am assuming that because I didn't call the constructor the list wasn't constructed and made it all fall over.

Selecting user with asp.net mvc

I have a list of users and if you click on a user there has to be create a new message.
But every time I click on a user id is 0
I have this:
action method:
public ActionResult StuurBericht(int id = 0, string onderwerp = "")
{
using (var rep = new GebruikerRepository(Context.Klant.Id))
{
var model = PersoneelsDossierService.GetPersoneelsDossierMutatieModel(Context.Klant.Id, GetMutatieRol(), int.Parse(Context.Gebruiker.ExternId), Gebruiker.DienstverbandId, Gebruiker.DienstverbandId, "Functionarissen");
model.Functionarissen = PersoneelsDossierService.GetFunctionarissen(Context.Klant.Id, Gebruiker.DienstverbandId);
BeveiligingService.ControleerGebruikerVanKlant(Context.Klant.Id, Context.Gebruiker.Id);
if (id > 0)
{
ModelState.Clear();
var modelMessage = new Message();
modelMessage.GebruikerId = id;
modelMessage.Onderwerp = string.Format("RE: {0}", onderwerp);
return View(model);
}
}
return View();
}
and this is the view:
#model List<SDB.Models.Stamtabel>
#{
var ItemsByAccordatieFunctieGroep = Model.GroupBy(a => a.Code);
<div class="row">
#foreach (var Accordeerders in ItemsByAccordatieFunctieGroep)
{
<div class="col-md-4">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading blue">#Accordeerders.Key</div>
<!-- List group -->
<ul class="list-group">
#foreach (var Accordeerder in Accordeerders)
{
<li class="list-group-item">
#Accordeerder.Omschrijving
</li>
}
</ul>
</div>
</div>
}
</div>
}
So my question is:
How to return the correct user and that you will get the correct id?
Thank you
this has to be the link for new message:
SelfService/Profiel/Nieuw?id=6240&onderwerp=test
So the controller is: Profiel.
But now the link is this:
/PersoneelsDossier/StuurBericht/0?onderwerp=HRM%20Management
So the controller link is incorrect.
Your #Url.Action is wrong, it should be:
#Accordeerder.Omschrijving

System.NotSupportedException was unhandled by user code, LINQ to Entities does not recognize the method

I am new in MVC asp.net i am developing a project where i want to add floors sequence wise. Want to start sequence from 0.
Message=LINQ to Entities does not recognize the method 'NTB.Floor LastOrDefault[Floor](System.Linq.IQueryable1[NTB.Floor], System.Linq.Expressions.Expression1[System.Func`2[NTB.Floor,System.Boolean]])' method, and this method cannot be translated into a store expression.
Controller:
public ActionResult Create(int id)
{
var cfloorno = 0;
//if (bid > 0)
//{
var lastfloor = db.Floors.Last(x => x.BuildingId == id);
if (lastfloor != null)
{
cfloorno = lastfloor.FloorNo.GetValueOrDefault() + 1;
}
//}
var building = db.Buildings.ToList();
ViewBag.Building = building;
var type = db.FloorTypes.ToList();
ViewBag.Type = type;
ViewBag.CurrentFloor = cfloorno;
ViewBag.buildingid = id;
return View();
}
[HttpPost]
public ActionResult Create(Floor f)
{
using (db)
{
db.Floors.Add(f);
db.SaveChanges();
}
return RedirectToAction("List");
}
View:
<input type="hidden" name="BuildingId" value="#ViewBag.buildingid" />
<div class="row">
<label class="col-sm-2 control-label">Floor #</label>
<div class="col-sm-10">
<input class="form-control" name="FloorNo" value="#ViewBag.CurrentFloor" disabled type="number">
#Html.ValidationMessageFor(model => model.FloorNo)
</div>
</div>

Setting A Variable With #Html.TextBox MVC3 ASP.Net

I'm working on a MVC3 ASP.Net application. I'm trying to figure out how to set the Quantity variable so when I pass it through to the controller with Html.ActionLink it has the correct number. Here's the view's code
#model IEnumerable<GreatVideosTrainingApplication.Models.Candy>
#{
ViewBag.Title = "Great Videos";
List<GreatVideosTrainingApplication.Models.Candy> candies = new List<GreatVideosTrainingApplication.Models.Candy>();
foreach (var candy in Model)
{
candies.Add(candy);
}
var grid = new WebGrid(candies);
var Quantity = 0;
}
<p>Welcome To Great Videos! The best source for your favorite DVDs and Blu-Rays</p>
<img src ="/Content/Images/dvd50.jpg" />
<p></p>
<img src="/Content/Images/bluray.jpg" />
<form method="post" action="/ShoppingCart/AddToCandyCart/"+item.CandyID >
#grid.GetHtml(#columns: grid.Columns(
grid.Column("Name"),
grid.Column("Price"),
grid.Column("Quantity", format: (item) => #Html.TextBox("Quantity", #Quantity)),
grid.Column("AddToCart", format: (item) => Html.ActionLink("Add To Cart", "AddToCandyCart", "ShoppingCart", new { id = item.CandyID, quantity = #Quantity }, ""))
)
)
</form>
I'm trying to set the value for the quantity with the Html.TextBox but it's not working. Keep in mind here I don't know javascript, and I'm extremely new to MVC3. Any and all help is greatly appreciated though.
public ActionResult AddToCandyCart(int id, FormCollection values)
{
// Add it to the shopping cart
var quantity = values["Quantity"];
var cart = ShoppingCart.GetCart(this.HttpContext);
// Retrieve the video from the database
var addedCandy = storeDB.Candies.Single(Candy => Candy.CandyID == id);
cart.AddToCandyCart(addedCandy, int.Parse(quantity));
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
The following code worked for me when including a textbox. I had trouble with the html helpers so I just wrote the code for the input box directly. I hope this helps.
grid.Column("Quantity", format: #<text><input name="Quantity" type="text" value="#item.Quantity"</text>))
Figured out the problem from mixing a variety of sources. Wanted to thank everyone. Here's the view.
#model IEnumerable<GreatVideosTrainingApplication.Models.Candy>
#{
ViewBag.Title = "Great Videos";
List<GreatVideosTrainingApplication.Models.Candy> candies = new List<GreatVideosTrainingApplication.Models.Candy>();
foreach (var candy in Model)
{
candies.Add(candy);
}
var grid = new WebGrid(candies);
var Quantity = 0;
}
<p>Welcome To Great Videos! The best source for your favorite DVDs and Blu-Rays</p>
<img src ="/Content/Images/dvd50.jpg" />
<p></p>
<img src="/Content/Images/bluray.jpg" />
<form method="post" action="../ShoppingCart/AddToCandyCart/" >
#using (Html.BeginForm()) {
#grid.GetHtml(#columns: grid.Columns(
grid.Column("Name"),
grid.Column("Price"),
grid.Column("Quantity", format: #<text><input name="Quantity" type="text" value="#Quantity"</text>),
grid.Column("AddToCart", format: #<text><input type="submit" value="Add To Cart" name="submit" /></text>)
)
)
}
</form>
Here's the Action Controller
[HttpPost]
public ActionResult AddToCandyCart(FormCollection values)
{
int id = 1;
string[] quantities = values["Quantity"].Split(',');
foreach (var item in quantities)
{
try
{
int quantity = int.Parse(item);
if (quantity >= 1)
{
// Add the candy to the shopping cart
var addedCandy = storeDB.Candies.Single(Candy => Candy.CandyID == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCandyCart(addedCandy, int.Parse(item));
}
}
catch (Exception e)
{
return View("Failed");
}
id++;
}
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}

Resources