Getting input value to action method. Mvc Core & AJAX - asp.net-mvc

I'm new to MVC Core and i'm having some struggles getting this right.
I've got a table filled with some basic values from my products, and what i want is to send a quantity value and an id of the product to my action method. The problem i'm having is that i'm able to send my product.ID to the action method, but i can't seem to get my input value. I tried using a button instead of my element and when i used that i managed to get the input but not the product.ID.
#model List<Product>
<div id="productList">
<form>
<table>
#foreach (var product in Model)
{
<tr>
<td>#product.Name</td>
<td>#product.Price</td>
<td><input type="text" name="quantity" /></td>
<td>
<a
asp-action="AddProductToCart"
asp-route-id="#product.ID"
data-ajax="true"
data-ajax-method="GET"
data-ajax-mode="replace"
data-ajax-update="#cartinfo">Add to basket</a>
</td>
</tr>
}
</table>
</form>
</div>
<div id="cartinfo">
</div>
My action methods parameters looks like this:
public IActionResult AddProductToCart(int id, int quantity)
I'm sure i'm missing some basic knowledge about how forms work so i'd really appreciate getting some help here. I've been trying to google this but i'm struggling with that as well. Thanks a lot

You can use javascript instead.
#model List<Product>
<div id="productList">
<form>
<table>
#foreach (var product in Model)
{
<tr>
<td style="visibility:hidden" class="pID">#product.ID</td>
<td>#product.Name</td>
<td>#product.Price</td>
<td><input type="text" name="quantity" class="qty"/></td>
<td>
<button class="btnAdd" >Add to basket</button>
</td>
</tr>
}
</table>
</form>
</div>
<div id="cartinfo">
</div>
java script
<script type="text/javascript">
$(document).ready(function () {
$('.btnAdd').click(function () {
var PID= $(this).closest("tr").find(".pID").text();
var Pqty= $(this).closest("tr").find(".qty").text();
AddtoCart(PID, Pqty);
});
});
function AddtoCart(pid,qty) {
$.ajax({
url: "#Url.Action("AddProductToCart", "Your Controller")",
type: 'GET',
data: { id: pid, quantity: qty},
datatype: 'json',
success: function (data) {
$('#cartinfo').html(data);
}
});
}
</script>
Hope this will help you!

Oh man, now i know what developers mean when they say that their code from 1 year ago is trash. Not sure if i should feel embarrassed or proud, haha.
My solution now would've probably been to post using JS. Also i wouldn't have placed my "asp-route-id="#product.ID" on an element, i could've just put it as a hidden input and posted it. Oh and that data-ajax-mode stuff confused me more than it helped, remove that for sure.
Note to self: Keep improving. :-)

You could try to put data-ajax attribute in the <form> ,and make the following changes in your view and the parameter in the action
<div id="productList">
<table>
#foreach (var product in Model)
{
<tr>
<form data-ajax="true"
data-ajax-url="/Your controllerName/AddProductToCart"
data-ajax-method="Post"
data-ajax-mode="replace"
data-ajax-update="#cartinfo">
<td>#product.Name</td>
<td>#product.Price</td>
<td>
<input type="text" asp-for="#product.quantity"/>
<input asp-for="#product.Id" hidden />
</td>
<td>
<input type="submit" value="Add to basket"/>
</td>
</form>
</tr>
}
</table>
Change the parameters to Model object , note that the parameter name must be consistent with the name of the data passed from the client side
[HttpPost]
public IActionResult AddProductToCart( Product product)
{
//the stuff you want
}

Related

How to pass value from submit button to mvc dynamically?

I started working with MVC from few days and got a question out of learning lot of ways to communicate between Controllers and Views in MVC
I have page that shows list of employees in tabular form.
Model is of type IEnumerable of Employee Model
It has three buttons they are Edit, Create, Delete, Details.
Requirement:
I used buttons so that all should be of HTTP Post request type because I do not want users to directly access them using URL requests.
Here is my view code:
#using (Html.BeginForm())
{
<p>
<input type="submit" name="CreateView" value="Create New(Post)" formaction="CreateView" formmethod="post" />
</p>
<table class="table">
<tr>
-------Headings of table-------
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.EmployeeName)</td>
<td>#Html.DisplayFor(modelItem => item.EmployeeGender)</td>
<td>#Html.DisplayFor(modelItem => item.EmployeeCity)</td>
<td>#Html.DisplayFor(modelItem => item.DepartmentId)</td>
<td>#Html.DisplayFor(modelItem => item.EmployeeDateOfBirth)</td>
<td>
<input type="submit" name="EditView" value="Edit(Post)" formaction="Edit" formmethod="post" /> |
<input type="submit" name="DetailsView" value="Details(Post)" formaction="Details" formmethod="post" /> |
<input type="submit" value="Delete(Post)" onclick="return confirm('Are you sure you want to delete record with EmployeeId = #item.EmployeeId')" />
</td>
</tr>
}
</table>
}
Here delete button works because I do not need the id of the employee.
But for other actions like editing, deleting and details viewing I need to pass Employees Id to controller. But how do I pass the Id to the controller using submit button.
In get requests types I used to pass like this:
#Html.ActionLink("Details", "Details", new { id = item.EmployeeId })
For single submit button I used to pass data like this
#using (Html.BeginForm("Details", "BusinessLayer", FormMethod.Post, new { id = item.EmployeeId }))
Can any one tell me the approach that I can fallow to achieve this?
You can have 3 separate form tags, one for each button. Just make sure you have an input field inside the form for the data you want to pass. For example if your action method is accepting the EmployeeId with a a parameter called EmployeeId, you should have in input hidden field with the same inside the form.
#model IEnumerable<Employee>
<table>
#foreach(var item in Model)
{
<tr>
<td>#item.EmployeeName</td>
<td>#item.EmployeeGender</td>
<td>#item.EmployeeCity</td>
<td>#item.EmployeeDateOfBirth</td>
<td>
#using(Html.BeginForm("Details","YourControllerName"))
{
<input type="hidden" name="EmployeeId" value="#item.EmployeeId" />
<input type="submit" value="Details" />
}
#using(Html.BeginForm("Edit","YourControllerName"))
{
<input type="hidden" name="EmployeeId" value="#item.EmployeeId" />
<input type="submit" value="Edit" />
}
#using(Html.BeginForm("Delete","YourControllerName"))
{
<input type="hidden" name="EmployeeId" value="#item.EmployeeId" />
<input type="submit" value="Delete" />
}
</td>
</tr>
}
Also remember, nested forms are invalid HTML. So make sure you do not have those.

How to send Id to Controller from Ajax Input Button

I have this grid which has an edit button. How do I add code to the input button so that the value of the Id is sent to the Controller?
#using (Ajax.BeginForm("EditLineItem", "OrderSummary", new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "content" })) {
<div id="summaryGrid">
<table >
<tr>
<th>Report Type</th>
<th>Borrower Name</th>
<th>Property Address</th>
<th>Est Comp Date</th>
<th>Report Price</th>
<th>Exp Fee</th>
<th>Disc.</th>
<th>Total Price</th>
</tr>
#{
foreach (var item in Model) {
<tr>
<td >#item.ReportName</td>
<td >#item.BorrowerName</td>
<td >#item.Address</td>
<td >#item.EstimatedCompletionDate</td>
<td >#item.ReportPrice</td>
<td >#item.ExpediteFee</td>
<td >#item.Discount</td>
<td >#item.TotalPrice</td>
<td >#item.Id</td>
<td ><input type="submit" value="Edit" /></td>
</tr>
}
}
</table>
</div>
}
just put a name on your input button.
<input type="submit" name="id" value="edit" />
Then on your action, you should be able to get the value for id.
If you want more complexity then you are going to have to rethink the way you are doing it. Most likely by writing your own JQuery methods.
$('input.edit').on('click', function (evt) {
evt.preventDefault();
var values = $(this).data();
$.post($(this).attr('href'), values, function (result) { /*do something*/ });
});
Html :
<a href="/edit/1" class="edit" type="submit" data-id="1" data-method="edit" />
That's a start, but you could probably tweak it to fit your needs. At that point, you don't need to wrap the whole table with the Ajax.BeginForm.
To add to Khalid's answer: I tested with this form:
<form method="get">
<input type="submit" name="Id1" value="Edit" id="id1" />
<input type="submit" name="Id2" value="Edit" id="id2" />
<input type="submit" name="Id3" value="Edit" id="id3" />
</form>
The post looks like this when clicking on the third button:
http://localhost:34605/HtmlPage.html?Id3=Edit
In other words, the browser passes the name of whichever button is clicked.
This is an example of getting the Id in the controller:
if (Request.QueryString.HasKeys()) {
string key = Request.QueryString.GetKey(0);
int id;
int.TryParse(key.Substring(2, 1), out id);
Response.Write("You selected id: " + id);
}
I have since found an even easier way of doing this:
Use the <button> element instead of <input>
With <button> you can do this:
<button type="submit" value="#item.Id" name="id">Edit</button>
and then in the controller, all you need is this:
public ActionResult EditLineItem(int id)
{ //Do something with id}
Note that this does not work with IE6.

Save all data of MVC4 html grid

Can anyone give me an example of saving all html grid data in one time. I have a view like this.
#model IList<SURVEY.Models.Question>
#using (Html.BeginForm("Index", "Survey", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-3" }))
{
#foreach(var item in Model)
{
<tr>
<td>#item.Ans1</td>
<td align="center">
<label>
<input type="radio" name="optionAS_#item.QuestionId" value="1" id="optionAS_1" onclick="disableAs(this,#item.QuestionId,1)"/>
</label>
</td>
<td align="center">
<label>
<input type="radio" name="optionAS_#item.QuestionId" value="2" id="optionAS_1" onclick="disableAs(this,#item.QuestionId,2)"/>
</label>
</td>
</tr>
}
}
I am getting null value for these controls in controller post.
[HttpPost]
public ActionResult Index(IList<Question> ques)
{
return View();
}
I am getting ques is null here. Can anyone tell me how can I resolve this?
You should use html helpers to bind properties of your model, your code might be as follows:
#for(var i = 0; i < Model.Count; i++)
{
<tr>
<td>#Html.HiddenFor(_ => Model[i].Id)
Model[i].Ans1
</td>
<td align="center">
<label>
#Html.RadioButtonFor(_ => Model[i].Name)
</label>
</td>
...
</tr>
}
and so for. HiddenFor helper is needed to create hidden input to send Id value to server to give you ability to identify you object. Take a look into Html Helpers in MVC and you will have your model back to server when form is submitted.

create div dynamically on click of a hyperlink in asp.net mvc

1.I want to dynamically generate div containing textbox with unique id on click of button
<input id="<%:rid %>" type="button" value="reply"/>
2.I also want to use jquery ajax mathod to carry the textbox data to ashx file .
Can anyone help me
code
var lineItemCount = 0;
$(document).ready(function () {
$(".commentbox input[type='button']").click(function () {
var id = $(this).attr("id");
alert(id);
var cid = id.substring(5);
var containerid = "container" + cid;
alert(containerid);
//Increase the lineitemcount
lineItemCount++;
//Add a new lineitem to the container, pass the lineItemCount to makesure
getLineItem()
// can generate a unique lineItem with unique Textbox ids
$(containerid).append(getLineItem(lineItemCount));
});
});
//Create a new DIV with Textboxes
function getLineItem(number) {
var div = document.createElement('div');
//Give the div a unique id
div.setAttribute('id', 'lineitem_' + number);
//pass unique values to the getTextbox() function
var t1 = getTextbox('txt_' + number + '_1');
div.appendChild(t1);
return div;
}
//Create a textbox, make sure the id passed to this function is unique...
function getTextbox(id) {
var textbox = document.createElement('input');
textbox.setAttribute('id', id);
textbox.setAttribute('name', id);
return textbox;
}
iteration through model in aspx page
<%var i=1;%>
<%foreach (var commentitem in item.commentsModelList)
{
<table border="0" class="commentbox">
<tr>
<%var rid = "reply" + i;%>
<div id="<%:containerid %>">
<td> <input id="<%:rid %>" type="button" value="reply"/>
</div>
</td>
</tr>
</table>
<% i++;}%>
I changed your markup little bit to get the corresponding id of items on my click events
HTML
<table border="0" class="commentbox">
<tr>
<td>Some Item text
</td>
</tr>
<tr>
<td>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
</table>
And the Script
$(function(){
$(".commentbox .btnReply").click(function(){
$(this).hide();
var id=$(this).attr("id").split("-")[1]
var strDiv="<input type='text' class='txtCmnt' id='txtReply-"+id+"' /> <input type='button' class='btnSave' value='Save' id='btnSave-"+id+"' /> ";
$("#container-"+id).html(strDiv);
});
$(".commentbox").on("click",".btnSave",function(){
var itemId=$(this).attr("id").split("-")[1]
var txt=$(this).parent().find(".txtCmnt").val();
$.post("/echo/json/", {reply: txt, id: itemId},function(data){
alert(data);
//do whatever with the response
})
});
});
Here is the jsfiddle example : http://jsfiddle.net/UGMkq/30/
You need to change the post target url to your relevant page which handles the ajax response.
EDIT : As per the comment about handing Multiple Divs
As long as you have the container div ids unique, it will work, I just changed the markup to include more than one item.
<table border="0" class="commentbox">
<tr>
<td>Some Item text<br/>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
<tr>
<td>Some Another Content here <br/>
<div id="container-2" ></div>
<input type="button" class='btnReply' id="reply-2" value="Reply" />
</td>
</tr>
</table>
Here is the sample :http://jsfiddle.net/UGMkq/44/
For the above output to be rendered, you probably want to write your razor syntax like this
<table border="0" class="commentbox">
#foreach (var commentitem in item.commentsModelList)
{
<tr>
<td>Some Another Content here<br/>
<div id="container-#(commentitem.Id)" ></div>
<input type="button" class='btnReply' id="reply-#(commentitem.Id)" value="Reply" />
</td>
</tr>
}
</table>
Instead of creating a new table for each item, I created a new row in existing table.

MVC list of checkboxes check and select to Action then to csv file

I have a view like:
#model IEnumerable<VectorCheck.Models.Invoice>
#{
ViewBag.Title = "Exportable Invoices";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.16.min.js" type="text/javascript"></script>
<script src="../../Scripts/Views/Export/index.js" type="text/javascript"></script
<header class="header">
<div class="headerText">
<h1>Exportable Invoices</h1>
</div>
</header>
#using (Html.BeginForm("Export", "Export")) {
<table>
<tr class="mainheader">
<th>Invoice Number</th>
<th>Date</th>
<th>Organisation</th>
<th>Total (Excl GST)</th>
<th>Status</th>
<th>Exported Date</th>
<th>
<select id="expenseSelect"></select>
<input type="submit" id="btnexport" value="Export" />
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.InvoiceNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.InvoiceDate, "{0:D}")
</td>
<td>
#Html.DisplayFor(modelItem => item.Organisation.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalExcludingGst)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.DisplayFor(modelItem => item.ExportedDateTime)
</td>
<td class="centered">
<input type="checkbox" class="exportcheckbox" data-invoiceid=#item.InvoiceId />
</td>
</tr>
}
</table>
}
<div>
#Html.ActionLink("Back to Summary", "Index", "Invoice")
</div>
Ok, so see how each checkbox has an attribrute data-invoiceid=#item.InvoiceId. Well I'm trying to get to an action method the Ids of all the invoices that have had their checkboxes checked. Also I'm trying to get the id of the selectlist expenseSelect which has options added to it on page load via jquery. I managed to achieve this with jquery and then sending the data with a $.post. The problem is in the file I'm sending the info to:
public ActionResult Export()
{
...
var csvData = _utility.GetCsvData(data);
return File(Encoding.UTF8.GetBytes(csvData), "text.csv", "invoices.csv");
}
brings up a save/open file dialog. I'm been informed this won't work for the jquery ajax call and I need to post the info back using a submit.
That's fine but now I have no idea how to send the select id and a list of the ids of the checked checkboxes to the method. Can anybody show me how to go about this?
You don't need any HTML5 data-* attributes since they are not sent to the server when you submit the form. In order to send their values you will have to use AJAX but this won't work with file downloads. So simply give your checkboxes a name:
<td class="centered">
<input type="checkbox" class="exportcheckbox" name="ids" value="#item.InvoiceId" />
</td>
and then on the server the default model binder will automatically construct an array of the ids of the checked items:
[HttpPost]
public ActionResult Export(int[] ids)
{
byte[] data = ...
return File(data, "text/csv", "invoices.csv");
}
Depending on the type of InvoiceId you might need to adjust the type of the action argument.
Radically changing my answer...
You could dynamically add a hidden IFRAME to your page. The IFRAME src can take your selected "ids" as a querystring parameter. This should get your your download dialog.
Got some help with the jquery from here: JQuery: Turn array input values into a string optimization
var selectedIdsArray = $(":checked").map(function(){return $(this).attr('data-invoiceid');});
var url = '#Url.Action("Export", "Export")?csv=' selectedIdsArray.get().join(',');
$('body').append("<iframe style='visibility:hidden' src='"+url +"'/>");

Resources