Hi i want to create table that has as many rows as user can set in input field.
how to do that instead of 5 in for loop i have value specified in input tag ?
#Using (Html.BeginForm("AddNewProces", "Admin", FormMethod.Post))
#<input type="number" value="5" min="1" name="rowsNumber" />
#<table>
#For i As Integer = 0 To 5
#<tr>
<td>Row #i</td>
</tr>
Next i
</table>
End Using
EDIT:
Ok i decided to change some things but now it still doesent work ;/ this is what i try now:
<script type="text/javascript">
$('.rowsNumber').on('input', function () {
alert("Value Changed");
});
</script>
and here is my htlm.textboxfor
#Html.TextBoxFor(Function(m) m.NumberOfRows, New With {.class = "rowsNumber"})
You would need to do this client-side, not server-side. The server-side code can't read the value of the input before the page has even been rendered.
So your view markup would simplify:
#Using (Html.BeginForm("AddNewProces", "Admin", FormMethod.Post))
#<input type="number" value="5" min="1" name="rowsNumber" />
#<table id="myTable">
</table>
End Using
Then you'd attach a JavaScript handler to the input to modify the table. It might have a structure that's something like this:
$('input[name="rowsNumber"]').on('input', function () {
var existingRowCount = $('#myTable tr').length;
var newRowCount = parseInt($(this).val());
if (newRowCount == existingRowCount) {
return;
}
if (newRowCount > existingRowCount) {
// append new rows to the table
}
if (newRowCount < existingRowCount) {
// remove trailing rows from the table
}
});
Related
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
}
EDIT:
Here is the exact problem that I have demonstrate, please have a look and as soon as I click the submit button it post back and lost its state and as you can see in the sample code I have three pages I'm posting the form
1) EmployeeForm, 2) EmployerForm, 3) ContractorForm
https://dotnetfiddle.net/wVtwgW
How do I persist the checkbox?
Once I post the page and it reloads the same page if I have my data-model invalid and it display the error message on the screen but the problem is that, it hides the fieldset and the user has to click the checkbox again to show the fieldset.
my question is: how can I still show the fieldset and show the error message in it?
//my scripts that shows the fieldset
<script>
$(document).ready(function() {
$('#Employee').change(function() {
if (this.checked) {
$('#emp').show();
}
});
});
</script>
//it shows the fieldset with checkbox:
<fieldset class="fieldset-auto-width">
<legend>
Select Employee
</legend>
<table width="auto">
<tr>
<th>
Employee
</th>
<td>
#Html.CheckBox("Employee")
</td>
</tr>
</table>
</fieldset>
//my form where I have all the input text and button etc...
<fieldset id="emp" style="display: none" class="fieldset-auto-width">
<legend>
Employee Display
</legend>
#using (Html.BeginForm("EmployeeServer", "EmployeeForm", FormMethod.Post))
{
#Html.ValidationSummary(true)
<div>..... </div>
}
</fieldset>
Instead of using #Html.CheckBox() use #Html.CheckBoxFor()
<td>
#Html.CheckBoxFor(m => m.Employee)
</td>
this will retain the state of the checkbox when you return the model state errors..
in your javascript, just call the $("#Employee") change event after the page loads..
$(document).ready(function() {
$('#Employee').change(function() {
if (this.checked) {
$('#emp').show();
}
});
$('#Employee').trigger("change");
});
Set the Fieldset display value when view is rendered
<fieldset id="emp" style="#(Model.Employee ? "": "display: none")" class="fieldset-auto-width">
<legend>
Employee Display
</legend>
#using (Html.BeginForm("EmployeeServer", "EmployeeForm", FormMethod.Post))
{
#Html.ValidationSummary(true)
<div>..... </div>
}
</fieldset>
this will hide the fieldset if Model.Employee = false or display it if Model.Employee = true.
Just do it with JavaScript. Look for the rendered element from the validation summary helper, and if it exists then you can show your employee form. You can add it to your already executing script like this:
$(document).ready(function() {
$('#Employee').change(function() {
if (this.checked) {
$('#emp').show();
}
});
//check for validation summary elements
if($('.validation-summary-errors').length > 0){
//and show previous entry if present
$('#emp').show();
}
});
I am new to knockoutJS. I am working on an MVC application where I want to implement knockoutJS but the scenario is bit different.
I have a page where I am showing a list. I have 3 links on the page and on click of them I am adding partial views to page accordingly. What I want to do is that whenever I add values/data to partial views, the list which is on page should be updated with knockout. In other words I want to add value to observable array when I save data from partial view.
Please let me know if this is possible or I should keep it in jquery only.
Here is the code:
Main view:
<input type="button" value="Add Partial View" onclick="LoadPartial();" />
<div id="dvContent"></div>
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script>
function LoadPartial() {
$.ajax({
url: "/home/index",
dataType:"html",
type: "GET",
success: function (data) {
$("#dvContent").html(data);
}
});
}
</script>
<script>
function AppViewModel() {
var self = this;
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function () {
self.people.push({ name: "New at " + new Date() });
};
self.removePerson = function () {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
</script>
Partial View:
<table>
<tr>
<td>Add new Row</td>
<td><input type="button" value="Add" data-bind="click: addPerson"/></td>
</tr>
</table>
Thanks,
JsHunjan
It is easy to accomplish with Knockout. You need to show some code that you have tried though if you want to get some help. I will post a general answer but it isn't going to fix your use case exactly, just basically -
Create an object to hold your new item, you can do this either in the parent or the child view model, but if you do it in the child you need to pass it back to the parent.
Once you hit a save button or add or whatever in the child view model just do a .push() into the observableArray that you created ex... - myObservableArray.push(newItem());
Knockout will recognize all of the changes taking place and perform the actions you want automatically.
Hope this helps.
I'm fetching an array of viewmodels from my controller using jquery+json. I then build a form where each row in a table represents one viewmodel.
My question is: How should I name each form element so that I can get it to my controller action like this:
public ActionResult Update(MyViewModel[] models)
{
}
Edit: I'm using jquery-tmpl to generate the form, and I'm also trying to figure out how to get an index variable in it (if that's needed for the form generation).
I managed to get it working.
My jquery template:
<script id="wagonTemplate" type="text/x-jquery-tmpl">
<tr>
<td>
<input type="checkbox" value="true" class="wagoncheck" name="wagons[${$item.getIndex()}].IsSelected" />
</td>
<td>
<input type="text" name="wagons[${$item.getIndex()}].WagonId" value="${WagonId}" style="width:120px" />
</td>
<td>
<input type="text" name="wagons[${$item.getIndex()}].WagonNumber" value="${WagonNumber}" style="width:20px" />
</td>
</script>
Method that loads the template:
function loadWagons(trainId, partId) {
$.getJSON('/train/wagons/' + escape(trainId) + '?partNo=' + partId, function (data) {
$wagons = $('#wagons tbody');
$wagons.empty();
// the function used in the template to get an index.
var tmplOptions = {
getIndex: function getIndex() {
return $.inArray(this.data, data);
}
};
$("#wagonTemplate").tmpl(data, tmplOptions).appendTo($wagons);
});
}
In other words:
To get a YourModel[] items argument in your controller action you need to name the items as items[0].MyProperty' where0` should correspond to the index in the array.
To get an index in a jquery template, just use pass a method in the options to the template function. I'm using a slightly modified version of the answer found here. Passing the item as done in that answer is not necessary as this points on the current item.
Hi i am new to ASP.NET MVC. I am not sure how to deal with Check box or Radio Button to get values when they are clicked. Can any one help me? I am providing a simple code that might help you understand what i meant to be. Please share examples.
<script type="text/javascript" >
function check(browser)
{
document.getElementById("answer").value=browser;
} </script>
<form action="">
<input type="radio" name="browser"
onclick="check(this.value)"
value="Internet Explorer"/>Internet
Explorer<br />
<input type="radio" name="browser"
onclick="check(this.value)"
value="Firefox"/>Firefox<br />
<input type="radio" name="browser"
onclick="check(this.value)"
value="Netscape"/>Netscape<br />
<input type="radio" name="browser"
onclick="check(this.value)"
value="Opera"/>Opera<br />
<br />
Your favorite browser is: <input type="text" id="answer"
size="20"/> </form>
controller code
public ActionResult Index()
{
ViewData["list"] = new[]
{
new SelectListItem {Text = "InternetExplorer", Value = "InternetExplorer"},
new SelectListItem {Text = "Firefox", Value = "Firefox"},
new SelectListItem {Text = "Safari", Value = "Safari"},
new SelectListItem {Text = "Opera", Value = "Opera"}
};
return View();
}
[AcceptVerbs(HttpVerbs.Post),ActionName("Index")]
public ActionResult IndexPost(string browser)
{
// ...
}
view code
<% using (Html.BeginForm()) { %>
<% foreach(var item in (IEnumerable<SelectListItem>)ViewData["list"]) { %>
<label>
<% = Html.RadioButton("browser", item.Value) %>
<% = item.Text %></label>
<% } %>
<input type="submit" value="Select" />
<% } %>
<script type="text/javascript" src="<% = Url.Content("~/Scripts/jquery-1.3.2.js") %>" ></script>
<script type="text/javascript">
$(function() {
$("form:first").submit(function(e) {
e.preventDefault();
alert($(this).find(":radio:checked").val());
});
});
</script>
If you want browser value in action, you coding in IndexPost method.
or you want in javascript, onsubmit or onclick(and other) event handling, get checked radiobutton value at jQuery.
This was logic taken from: http://byatool.com/mvc/asp-net-mvc-how-to-handle-multiple-checkboxes-with-viewsactions-jquery-too/. I simply modified it very minimally.
----------
HTML Part|
----------
{form action="/Test/CheckForIds/" method="post"}
{div}
{input type="checkbox" name="IdList" value="1" /}
{input type="checkbox" name="IdList" value="2" /}
{input type="checkbox" name="IdList" value="3" /}
{input type="checkbox" name="IdList" value="4" /}
{/div}
{div}
{input type="submit" value="go" /}
{/div}
{/form}
----------------
Controller Part|
----------------
{AcceptVerbs(HttpVerbs.Post)} _
Function GroupPageSend(ByVal selectedObjects() As String) As ActionResult
{!--- YOUR CODE GOES HERE ---}
EX//
For Each item In selectedObjects
If i = 0 Then
string = Trim(item)
i = i + 1
Else
string = string & "," & Trim(item)
End If
Next
End Function
The above will gather values from selected checkboxes and will allow you to manage results.
Keep in mind all { = < and all } = >
I am probably not getting your question, but your sample will work well.
When you submit the form and the controller's method is called asp.net mvc will set the "browser" parameter to the value of the selected radio button's value.
hai friend try this,
<asp:RadioButton ID="RadioButton1" runat="server" onmousedown="yourjsfunc();" />