Submit Html form with a specific model - excel

I am using MVC, Razor, Knockout, typescript in my application. Need to prepare a excel file with a model/dataset that is set at client side. I am using the following code but the problem i understand is that the dataset is being taken as string and not exactly like the model it is supposed to take as. Here is the code
This is observable (dataset)
vmExportData = ko.observableArray<ExcelModel>([]);
Push data to the dataset
vmExportData.push(new ExcelModel (
e.sender.data()[i].Id,
e.sender.data()[i].Name,
e.sender.data()[i].Address1,
));
Html code, to prepare excel file (at the controller)
#using (Html.BeginForm("ExportToExcel", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div data-bind="css:{hidden: true}">
<input type="text" data-bind="value: vmExportData" />
</div>
<input class='excelIcon' type="submit" data-ux-access="true" value="">
}
Controller method :
public ActionResult ExportToExcel(ExportModel exportModel)
{
The problem is, the exportModel parameter value is coming as null ! Any other way out to get it to work ? Is there a way to make excel at client side and render as well ?

Try setting name="exportModel" on your tag.
Also make sure to have an [HttpPost] on top of your controller action, since your form method is post.
What does the ExportModel class look like?

Related

How can i check Template and get the value of it?

Well My purpose is to use checkbox to pick a template,after that it will be added to a database
but when i try to get the code of template into value it always display undefined.
Interface
Html Code:
<input type="checkbox" id="templatepick" name="picker" value="item.templatebodyclient" (change)="displaydata($event)">
templatebody attribut have the html of our template so i tried to get it from the checked template value to be set in database
Typescript code:
displaydata(event: { checked: any; }){
console.log("",event.checked) }
Any idea how i can solve this ? or another idea could be useful and thanks
You may use:
HTML
<input type="checkbox" id="templatepick" name="picker" [value]="item.templatebodyclient" (change)="displaydata($event)">
TS
displaydata(event: any) {
console.log(event.currentTarget.checked)
console.log(event.target.checked)
}

.net core 2.0 Razor pages VS 2017 Tabular data download

I am new to web development with Razor pages .net core VS 2017.
I have index page that lists my data in the form of rows & columns using EF core Model.
I am also providing data filtering options via DropDowns and search box.
I want to export this tabular filtered/unfiltered data to excel. --- For which i think i can use NPOI nuget package (http://www.talkingdotnet.com/import-export-excel-asp-net-core-2-razor-pages/).
I want to do this using asp-page-handler with button click.
Questions:
1. Will this be GET request or POST ?
How to pass data (e.g. model object with all data) to the page handler ?
Any help is Appreciated.
Thanks.
For your first question about using GET or POST, both methods can be used but I personally use the POST method for cases like this.
For your second question I would not send to server all the filtered data but I would pass the filtering information which will be used in order to generate the data and export them to an Excel file.
Update 1
I made a simple example for you. Type the following html in your cshtml file:
<form method="post">
<button type="submit" class="btn btn-info"> Export</button>
<input asp-for="Value1" type="hidden" value="1" />
<input asp-for="Value2" type="hidden" value="2" />
</form>
The two inputs will be used in order to submit to the server values which will be used in order to filter your data. The following OnPost will return a static file but you can write your own code in order to return the filtered data and return them to the browser.
[BindProperty]
public int Value1 { get; set; }
[BindProperty]
public int Value2 { get; set; }
public ActionResult OnPost()
{
// example of returning a file
return File("~/Images/accounts.png", "image/png", "FileNameForBrowser.png");
}
Thanks #pitaridis for your valuable inputs.
i ended up doing like this:
` <a asp-page="./Index" asp-page-handler="Export"
asp-route-param1 = "#Model.data1"
asp-route-param2 = "#Model.data2"
asp-route-param3 = "#Model.data3"
class="btn btn-info">
Export
</a>
`
Page handler is OnGetExportAsync(...).On handler call I am getting page refresh, Not sure Why I have to again repopulate all the controls. Any idea on this ?
or other option could be to use the OnGetAsync() method & by passing a param that identify it as file download ?

The required anti-forgery cookie "__RequestVerificationToken" is not present. I'm out of ideias

I'm developing a backend in MVC 5 for a client to update in their website. However I got across this error:
Error Image
This is the controller with the methods with the AntiForgeryToken
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
[System.web.Mvc.AuthorizeSectionccess(sectionname = "IT")]
public ActionResult Create()
{
return View();
}
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
[System.web.Mvc.AuthorizeSectionccess(sectionname = "IT")]
[System.web.Mvc.AuthorizePermitionAccess(PermissonType = "Add")]
[HttpPost]
public ActionResult Create(Welcome_conteudoPage model)
{
DB.Welcome_conteudoPage.Add(model);
DB.SaveChanges();
return Redirect("Index");
return View(model);
}
And this is the View
#using (Html.BeginForm("Create", "ConteudosPageController", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
#Html.TextAreaFor(model => model.ConteudoStandard)
</div>
<div>
<input type="submit" value="Inserir" class="btn btn-primary"/>
</div>
<div>
Texto:
#Html.DisplayFor(model => model.ConteudoStandard)
</div>
}
I'm using the AntiForgeryToken on both ends and still get that error. I know that there are thousands of questions like this but I've tried all of the proposed solutions for 3 days and without any result.
EDIT: I forgot to mention that the view is going to call the controller and model for a tinyMCE Editor
It might not be the answer, however, you may have misunderstood what the anti forgery token does and where to use it.
Firstly, when you use #Html.AntiforgeryToken in a view, it registers something in either the session or cookie (can't remember which).
The validate anti forgery token attribute looks for that token and matches it against the passed in token in the hidden field. If it doesn't match, then most likely the post request didn't come from your view.
The thing to note, is that this requires a body parameter on the request to send in the token. You wouldn't have this on requests that don't have a body. A Get request doesn't have a body, and therefore doesn't need the validateantiforgerytoken attribute on it.

Update #Html.Partial() View only

I am not looking for a javascript/jquery answer. I can do that, but I feel like it breaks the purpose. This seems like something that should be possible without javascript.
I'm trying to get a simple listbox selection to update an #Html.Partial section, and I'm not exactly sure what to do. Everything loads initially just fine. After I submit, however, I am not quite sure how to 'attach' to my partial view to update it.
The purpose here is to only load the listbox one time, and let them view or request as many new reports as they want without reloading. If it's not possible, that's fine, I can use one page, reload the listboxes, and it will work. I just don't see why I would need to go to the database to reload the listbox items every time they view or request a report.
"master" html page:
#using TCTReports.Models
#model ReportViewModel
<h2>My Reports</h2>
<div class="row">
<div class="col-md-6">
<h3>Select Report</h3>
#using (Html.BeginForm("GetReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedMyID, Model.myLB)
<input type="submit" value="View" />
}
</div>
<div class="col-md-6">
<h3>All Reports</h3>
#using (Html.BeginForm("ReqReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedAllID, Model.allLB)
<input type="submit" value="View" />
}
</div>
</div>
#Html.Partial("_Msg")
_Msg is super simple atm. It would eventually be a report viewer, for now, it looks at #Viewbag...
<h2>#ViewBag.Message</h2>
Controller submit actions (I get my selected value just fine. currently on void but was ActionResult with Views - but I don't feel like that is correct either, as it completely overwrites the page (even with PartialView) and I lose my listboxes and _layout...):
public void GetReport(ReportViewModel model)
{
var myID = model.SelectedMyID;
ViewBag.Message = "Report: " + myID.ToString() + " Selected.";
//return PartialView("_Msg","Test");
}
public void ReqReport(ReportViewModel model)
{
var allID = model.SelectedAllID;
ViewBag.Message = "Report: " + allID.ToString() + " Requested.";
//return PartialView("_Msg", "Test");
}
Ok, so how would I go about updating _Msg and refreshing only the #Html.PartialView() section of my master html page? I played with #sections briefly but didn't make much progress.

Symfony 2: parsing input value from a twig for a simple search function

I come back with a symfony2 problem I have.
I'm trying to make a really simple "search form" to display some posts of a blog. To not overkill it, I've decided to create the form directly in the twig like this:
<form class="form-search" method="post" action="{{ url('search_route') }}">
<input type="text" placeholder="Search" class="input-medium search-query" name="search">
<button type="submit"><img src="/img/search.png" alt="search" /></button>
</form>
In my controller I'm trying to find a way of how to pass the value of the input in my query. Here is the code of the searchAction():
use Symfony\Component\HttpFoundation\Request;
/..
public function searchAction(Request $request)
{
$data = $request->request->all();
$dql = "SELECT a FROM PfBlogBundle:Article a WHERE a.title LIKE '{$data['search']}' ORDER by a.id DESC";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$this->get('request')->query->get('page', 1)/*page number*/,
4/*limit per page*/
);
return $this->render('PfBlogBundle:Default:blog.html.twig', array('pagination'=>$pagination));
}
the fact is that if I print_r($data), I have the value sent through the input.. My problem is really to pass it in the query I think.. I'm developing locally and get a server error in the browser when I hit submit :/
Any idea?

Resources