Pass parameters to actionresult from jsonresult - javascript

I wrote code to filter results like following image ,
once after it filter I want to send model values of following field as parameters to another controller method, I can call that method once I click Generate Report button
this is view file
#model project_name.Models.SearchVM
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
....
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
...............
<div class="row">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Generate Report" class="btn btn-success submit" onclick="location.href='#Url.Action("ReportExport", "Home", new { type = Model.Type , ............. })'" /> <button id="search" type="button" class="btn btn-success submit">Search</button>
</div>
</div>
</div>
}
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Product name</th>
<th>Type</th>
.........
<th>Action</th>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<table id="template" class="table" style="display: none;">
<tr>
<td></td>
<td></td>
<td></td>
........
<td><a>Edit</a></td>
</tr>
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker({
dateFormat: 'yy/mm/dd', changeMonth: true,
changeYear: true, yearRange: '1910:2015'
});
});
</script>
<script type="text/javascript">
var url = '#Url.Action("FetchProducts")';
var editUrl = '#Url.Action("Edit")';
var type = $('#Type');
..............
var template = $('#template');
var table = $('#table');
$('#search').click(function () {
table.empty();
$.getJSON(url, { type: type.val(), ......, function (data) {
$.each(data, function (index, item) {
var clone = template.clone();
var cells = clone.find('td');
cells.eq(0).text(item.ID);
cells.eq(1).text(item.Name);
cells.eq(2).text(item.Type);
........................
cells.eq(7).text(item.Status);
var href = '#Url.Action("Edit")' + '/' + item.ID;
cells.eq(8).children('a').attr('href', href);
table.append(clone.find('tr'));
});
});
});
</script>
}
I want to call and send parameters to ReportExport method once I click Generate Report button
But I'm getting null values , I think this is because of I'm doing searching using Json , So How can I get Type value and send that as parameter ,
[HttpGet]
public ActionResult ReportExport(string id, string type, ...........)
{

#Url.Action()
is razor code. It's evaluated on the server before it's sent to the view. So you have to build your URL like quoted above.
var url = $(this).data('baseurl') + '?type=' + $('#Type').val() + '&category=' + $('#Category').val() + ...;

Your 'Generate Report' button includes #Url.Action("ReportExport", "Home", new { type = Model.Type, ... which is razor code. Razor code is parsed on the server before its sent to the view so its generating the route values based on the initial values of your model, not the edited values.
You can use jQuery to build you url based on the form controls.
Html
<input type="button" id="report" data-baseurl="#Url.Action("ReportExport", "Home")" value="Generate Report" class="..." />
Script
$('#report').click(function() {
// build the url
var url = $(this).data('baseurl') + '?type=' + $('#Type').val() + '&category=' + $('#Category').val() + ......;
// redirect
location.href = url;
});

Related

Building a table that pulls data from MongoDB that filters in real time, and sorts alphabetically

As the title suggests, that is what im attempting to do, but are at a lost. My best attempt is the following:
This is the nodejs code that renders the HTML page and gets the user input from HTML
app.get('/search/species', (req,res) => {
diseaseModel.find({matched: current_matched}, function (err,disease){
res.render('species', {
diseaseList: disease,
});
});
})
app.post('/search/species', async(req,res) => {
var desc = req.body.desc;
await diseaseModel.updateMany({matched: current_matched, "$text":{"$search" : `\"${desc}\"`}}, {$inc: {matched: 1}});
current_matched ++;
res.redirect(302, '/search/species');
}
}
});
})
This is the HTML page that I uses to collect user input and return the filtered options:
<form action = "/search/species" method = "POST" id="submitMessage" class="field has-addons">
<input class="form-control input is-primary" name = "desc" id = "desc" type="text" style="width: 100%;" placeholder="Enter a Description" required/>
<button type="submit" class="button is-primary" id="send">Send</button>
</form>
</div>
</div>
</section>
<table class = "content-table" align="center" style="margin: 0px auto;">
<thead>
<tr>
<th>Name</th>
<th>Species</th>
<th>Vector</th>
<th>Agent</th>
</tr>
</thead>
<tbody>
<%diseaseList.forEach(disease =>{%>
<tr data-href= 'http://localhost:8080/info?id=<%=disease.id%>'>
<th><%=disease.diseaseName%></th>
<th><%=disease.species%></th>
<th><%=disease.vector%></th>
<th><%=disease.agent%></th>
</tr>
<% })%>
</tbody>
</table>
</div>
</section>
<script>
$(document).ready(function() {
$(document.body).on("click", "tr[data-href]", function() {
window.location.href = this.dataset.href;
})
});
But this doesn't refresh in real time, as in when i type a character, it doesn't start filtering. Would I be able to do this via AJAX? Also how would I list MongoDB data out in the table in alphabetical order?

Pass the value of a button to a hidden field and save it to database

So my design is I have multiple display fields and one hidden field. Besides each row there are two buttons accept and reject.my point is when I click a button its value pass to the hidden field and submits automatically in the database.
when I try my code the button doesn't pass anything and I tried all the solutions related to this topic and nothing is working. what am I doing wrong?
controller:
[HttpGet]
public ActionResult Add_Fulfillment ()
{
var getData = db.TBL_Request.Include(x=>x.TBL_Accounts).Include(x=>x.TBL_Accounts_LOBs).ToList() ;
var add_fulfillment = new Add_Fulfillment();
var ful_ = new fulfillmentVM();
foreach (var data in getData)
{
List<Add_Fulfillment> fulfillment = db.TBL_Request.Select(i => new Add_Fulfillment
{
Request_ID = i.Request_ID,
Employee_no = i.Employee_no,
Operation_Date = i.Operation_Date,
Fulfillment_Rate = i.Fulfillment_Rate ??0,
Account_Name = i.TBL_Accounts.Account_Name,
LOB = i.TBL_Accounts_LOBs.LOB,
Status = i.Inserted_by
}).ToList();
ful_._Requests = fulfillment;
}
return View(ful_);
}
[HttpPost]
public ActionResult Add_Fulfillment_Accept(int Request_ID , int? Status)
{
var user= db.TBL_Request.Find(Request_ID);
//hiddenfieldvalue assigns it to the field in the database i want to update
db.SaveChanges();
return RedirectToAction("Add_Fulfillment");
}
[HttpPost]
public ActionResult Add_Fulfillment_Reject(int Request_ID)
{
return RedirectToAction("Add_Fulfillment");
}
the view
#model Staff_Requisition.Models.fulfillmentVM
#{
ViewBag.Title = "Add_Fulfillment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add_Fulfillment</h2>
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Plain Page</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<table class="table">
<tr>
<th>
Employee_no
</th>
<th>
Operation_Date
</th>
<th>
Fulfillment_Rate
</th>
<th>
Account_Name
</th>
<th>
LOB
</th>
<th></th>
<th></th>
</tr>
#for (int i = 0; i < Model._Requests.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(x => Model._Requests[i].Employee_no)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Operation_Date)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Fulfillment_Rate)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Account_Name)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].LOB)
</td>
<td>
#Html.Hidden("Status" , Model._Requests[i].Status , new { id = "myEdit" })
</td>
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$("#btnAccept").click(function () {
$("#myEdit").val($("#btnAccept").val());
})
$("#btnReject").click(function () {
$("#myEdit").val($("#btnReject").val());
})
</script>
}
I solved it. the only issue was I didn't put the hidden field of the status inside the form .that's why it never passes the value. thank you for all your efforts though!
view:
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" onclick="accept(122)" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" onclick="reject(222)" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$('[name = "a_button"]').click(function () {
$('[name = "Status"]').val($('[name = "a_button"]').val());
})
$('[name = "button"]').click(function () {
$('[name = "Status"]').val($('[name = "button"]').val());
})
</script>

Hiding and un-hiding table div based off of data being returned

I have a table that I want to be hidden there is no data to be displayed.
I have a controller action that returns data to display for the table. If data is returned, I want the table to be show, otherwise I want it hidden. I have tried several approaches to this and it seems like my fix is working (for a few seconds) but then once the controller returns the model, the table becomes hidden again. I am doing something wrong. How can I fix this? Below is my code:
HTML:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "submitForm"}))
{
<div class="row">
<div>
#Html.DropDownList("CasinoID", Model.TerminalReceiptPostData.CasinoIdDDL, "Select Casino", new { id = "cIdSearch", #class = "custom-class-for-dropdown card" })
</div>
<div>
<input id="datepicker" class="datepicker-base card" name="Date" placeholder="MM/DD/YYY" type="text"/>
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary" id="search"> Search Transactions</button>
</div>
</div>
}
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Controller action:
[HttpPost]
public ActionResult Index(string CasinoID, DateTime Date)
{
//var id = Int32.Parse(Request.Form["CasinoID"].ToString());
var Cid = Request.Form["CasinoID"];
Cid = GetNumbers(Cid);
var id = Int32.Parse(Cid);
var model = TRBL.GetTransactionTestsData(id, Date);
model.TerminalReceiptPostData = TRBL.GetCasinosDDL();
return View(model);
}
and finally my JS function:
window.onload = function () {
$("#ReceiptsMainDiv").toggle();
var rowCount = $("#rowindex").length;
console.log(rowCount);
if (rowCount > 0) {
$("#ReceiptsMainDiv").toggle();
}
};
As you can see, the Form at the top contains the button, and the block below is the table that needs to be toggled.
Let me know if there is anything else you guys would need.
When you have results to show, <tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))"> will not produce ids of "rowIndex" (unlike what you might be expecting). Instead, you will have "rowIndex0", "rowIndex1", etc. Therefore, after rowCount will be zero, and your will not toggle.

How to bind dropdown value in mvc

I'm unable to bind the dropdown value. Maybe I'm missing something in my code. Here I'm attaching my view code.
<tr>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.DropDownList("ProofId", ViewBag.Idproofs as SelectList, new { #class = "form-control", id = "ProofType2", name = "ProofType2" })
</div>
</td>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.TextBoxFor(x => x.EvidenceData[1].ProofNumber, new { #class = "form-control", id = "IdNumber2", name = "IdNumber2" })
</div>
</td>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.TextBoxFor(x => x.EvidenceData[1].ProofImage, new { #class = "form-control", id = "ProofPic2", type = "file", name = "ProofPic2" })
<i class="fa fa-download" aria-hidden="true"></i> Download Image
</div>
</td>
</tr>
And this is my controller code:
public ActionResult EditProfile(string country)
{
if (!User.Identity.IsAuthenticated)
return new RedirectResult(Utility.Config("RedirectPath"));
var idprooflist = AccountManager.LoadProoftypes(country ?? "United States");
ViewBag.Idproofs = new SelectList(idprooflist, "ProofId", "ProofName");
UserRegistration UserProfileData = ProviderManagerBLL.GetProviderDetails(Convert.ToInt32(Session["UserID"].ToString()));
return View(UserProfileData);
}
The below should work for you:
<div class="form-group" style="margin-bottom:0px;">
#Html.DropDownList("ProofId", (SelectList)ViewBag.Idproofs, new { #class = "form-control", id = "ProofType2", name = "ProofType2" })
</div>
You are using a ViewBag to pass your values to the View and all you have to do is reference what you want from it. What you were doing before wouldn't work

how to handle partial view elements in javascript

please refer this code and it is for a partial view of my web application developed using mvc.
#model PortalModels.WholeSaleModelUser
#using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>WholeSaleModelUser</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</td>
</tr>
</table>
<div id="partial">
<table>
<tr>
<td>
<img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
</td>
</tr>
</table>
<script type="text/javascript">
function loadUserImage() {
var userImg = document.getElementById("blah");
var imgNm = $("#Name").value;
userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
alert(imgNm);
alert(userImg.src);
}
</script>
i need to handle the textchange event of this textbox in partial view using javascript code i have mentioned above
#Html.TextBoxFor(model => model.Name)
please somebody tell me how to handle the text change event of the above code line of textbox..
$document.on('blur', 'TextBox', function(){
//Do something
});
This format should work for any fields on a partial view. from here http://api.jquery.com/on/

Categories

Resources