How to pass value from submit button to mvc dynamically? - asp.net-mvc

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.

Related

Getting input value to action method. Mvc Core & AJAX

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
}

Html.BeginForm works but not Ajax.BeginForm

I have an ASP MVC app that is attempting to submit my ViewModel which has a property called Document on it that is an HttpPostedFileBase. The ViewModel binds fine when I use #Html.BeginForm, however if I change it to #Ajax.BeginForm and keep all things the same, it will bind the all the ViewModel properties EXCEPT for the HttpPostedFileBase property. Any advice?
Relevant Code:
[HttpPost]
public ActionResult Add(ViewModel vm)
{
return new HttpStatusCodeResult(200);
}
#using (Ajax.BeginForm("Add", "Home", new AjaxOptions() { HttpMethod = "Post" , AllowCache = false}, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(m => Model.Document.DocumentType);
#Html.HiddenFor(m => Model.Document.DocumentTypeId);
#Html.HiddenFor(m => Model.Document.File);
<div class="container">
<table>
<tr>
<td>
<input class="form-control" type="text" id="lblAllReceivables" /> </td>
<td >
#Html.TextBoxFor(m => m.Document.File, new { type = "file", #class = "inputfile", #name = "file", #id = Model.Document.DocumentTypeId, #accept = ".pdf, .doc, docx" })
<label id="lblUpload" for="#Model.Document.DocumentTypeId"><i class="fa fa-upload" style="margin-right:10px;"></i>File</label>
</td>
</tr>
<tr>
<td colspan="2" >
Comments:<br />
<div class="input-group" style="width:100%;">
#Html.TextAreaFor(m => m.Document.Comments)
</div>
</td>
</tr>
<tr>
<td colspan="2"><hr /></td>
</tr>
<tr><td colspan="2" > <input id="btnSubmit" class="btn btn-default btn-lg" type="submit" style="width:275px;" value="Submit Application" /><a class="btn btn-default">Cancel</a></td></tr>
</table>
</div>
}
I have found that the browser does not support uploading a file via xmlhttprequest, which is what ajax.beginform uses to post data (as do all browser ajax libs). If you are using a html 5 browser, you can use the new file api to upload the file. for older browsers, you use an iframe to post the file. google for jquery plugin that wrap both those functions or just use the iframe appraoch (it pretty trival).
In specific cases I prefer to use another plugins like DropzoneJS it's better to handle it and you can upload multiple files easy.

Dynamic Model Binding Partial View to Model MVC?

I'm trying to bind the model from the partial view to my main form. My Model workoutPlan only stores a list of WorkoutSets
public List<WorkoutSet> WorkoutSet;
In my main page. My form looks something like this:
#model WorkoutPlanObjects.WorkoutPlan
#using (Html.BeginForm("AddNewPlan", "Workout", FormMethod.Post))
{
if (Model != null)
{
<table id="workoutTable">
<tr>
<td>
#{Html.RenderPartial("~/Views/Partial/_AddNewPlan.cshtml", Model);}
</td>
</tr>
</table>
}
<input type="submit" id="submit" value="submit" />
}
and here's my partial view _AddNewPlan
#model WorkoutPlanObjects.WorkoutPlan
#if(Model!=null)
{
foreach (var item in Model.WorkoutSet)
{
#Html.TextBoxFor(a => item.Repeats)
}
}
I was able to update my partial view using ajax calls but when I try to submit the form, no values get passed. Here's the snippet of the code in chrome which shows the rendered partial view (excuse the formatting). Any solution for this?
I could see that the name of the rendered views are all the same item.Repeats. How should I change this partial view name to bind with the main page model?
<form action="/Workout/AddNewPlan" method="post">
<table id="workoutTable">
<tbody><tr>
<td>
<input id="item_Repeats" name="item.Repeats" type="text" value="1">
<input id="item_Repeats" name="item.Repeats" type="text" value="2">
<input id="item_Repeats" name="item.Repeats" type="text" value="3">
<input id="item_Repeats" name="item.Repeats" type="text" value="4">
</td>
</tr>
</tbody>
</table>
<input type="submit" id="submit" value="submit">
</form>
Change your foreach loop to a for loop so that the inputs are correctly named
foreach (iny i = 0; i < Model.WorkoutSet.Count; i++)
{
#Html.TextBoxFor(a => a.WorkoutSet[i].Repeats)
}
which will render
<input .... name="WorkoutSet[0].Repeats" type="text" value="1">
<input .... name="WorkoutSet[1].Repeats" type="text" value="2">
and allow the DefaultModelBinder to bind the collection.
Note property WorkoutSet will need to be IList. Alternatively you can create a custom EditorTemplate for WorkoutSet and use #Html.EditorFor(m => m.WorkoutSet)

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.

Resources