Delete button sending the value of another form - c#

I have the following code that creates multiple different forms within a for loop to delete the different values in a database:
#foreach (var item in Model.value)
{
<script>var temp = {'value' : '#item.name'}</script>
<form class="formStyle" id="allCurrentNames_#item.name" method="post" action="">
<input type="hidden" id="part_name_#item.name" value="#item.name"/>
<button class="partDelete" onclick="deletePart(temp);return false;">Delete</button>
</form>
}
The following is the deletePart(temp) function:
function deletePart(temp) {
var personName = $("input#part_num_"+temp.value).val();
var dataString = 'partnumber=' + partnumber;
$.ajax({
AJAX STUFF
})
}
Assuming I will have something like the following:
Person Name1 [DELETE]
Person Name2 [DELETE]
Person Name3 [DELETE]
Person Name4 [DELETE]
Person Name5 [DELETE]
Person Name6 [DELETE]
If I click Person Name3 it sends in the value of Person Name6 always no matter which Delete button I click.
Any help is much appreciated!
Thank you for your time!

Remove your javascript from html
#foreach (var item in Model.value)
{
<form class="formStyle" id="allCurrentNames_#item.name" method="post" action="">
<input type="hidden" id="part_name_#item.name" value="#item.name"/>
<button class="partDelete">Delete</button>
</form>
}
And change your javascript code like this
$('.partDelete').click(function(){
var $this = $(this);
var partnumber = $this.parent().find('input').val();
var dataString = 'partnumber=' + partnumber;
//ajax
return false;
});
$('.partDelete').click(function(){
var $this = $(this);
var partnumber = $this.parent().find('input').val();
var dataString = 'partnumber=' + partnumber;
alert(dataString)
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="formStyle" id="allCurrentNames_1" method="post" action="" onsubmit="return false;">
<input type="hidden" class="part_name" value="1"/>
<button class="partDelete">Delete</button>
</form>
<form class="formStyle" id="allCurrentNames_2" method="post" action="" onsubmit="return false;">
<input type="hidden" class="part_name" value="2"/>
<button class="partDelete">Delete</button>
</form>
<form class="formStyle" id="allCurrentNames_2" method="post" action="" onsubmit="return false;">
<input type="hidden" class="part_name" value="2"/>
<button class="partDelete">Delete</button>
</form>

A much simpler action could be setting a unique id to each person's name. You'll just need to replace two lines of code.
When building your forms, replace:
<input type="hidden" id="part_name" value="#item.name"/>
<button class="partDelete" onclick="deletePart();return false;">Delete</button>
with this:
<input type="hidden" id="part_name_#item.name" value="#item.name"/>
<button class="partDelete" onclick="deletePart(#item.name);return false;">Delete</button>
And in the deletePart js, replace:
function deletePart() {
var personName = $("input#part_num").val();
with this:
function deletePart(id) {
var personName = $("input#part_name" + id).val();

Your problem is in your javascript on this line:
var personName = $("input#part_num").val();
Since you are rendering these forms in a loop, you will have multiple input fields with part_num as the id. JQuery is going to give you the first instance found which matches your selector, which is why you are always posting the value of the first person.
You can easily fix this by figuring out which form the event came from and then selecting the correct part_num.
var personName = $('#correct_form_id #part_num').val();
Hope this helps!
EDIT: Adding some sample code
One approach could be to capture your form submit and handle it yourself. For instance:
$( "form" ).submit(function( event ) {
var personName = $(this).find('#part_num').val();
// Do what you want with this information
// prevents the form from posting, if that is desired
event.preventDefault();
});
Now you may have other forms on your page that you don't want to be caught by this handler, so you could add a class to the forms you are generating in your loop to verify that you are only capturing the correct events. Then your definition would look like:
$('form.some_class').submit(function(event)) {
...
});

Related

FormCollection not posting a input value

I'm trying to get two input values from a view and pass them to controller using FormCollection.
These values change is based in a double click in a table row as you can see in jquery code below.
When i tried the first time only with id_artigo it worked! Then, when i tried do the same with descricao, it return the same view because descricao isn't geting the value.
id_artigo is an integer and descricao is a string.
What am i doing wrong ?
public ActionResult Create(NebluViewModel necessidadeModel, FormCollection collection)
necessidadeModel.NecessidadesModel.id_artigo = int.Parse(collection["label"]);
necessidadeModel.NecessidadesModel.descricao = collection["labelD"];
<div class="form-group">
<span class="id-label"></span>
<input type="hidden" id="label" name="label" value="" />
</div>
<div class="form-group">
<span class="id-labelD"></span>
<input type="hidden" id="labelD" name="labelD" value="" />
</div>
<script>
$(document).ready(function () {
var table = $('#example').DataTable();
$('#example tbody').on('dblclick', 'tr', function () {
let $tr = $(this);
if ($tr.hasClass('selected')) {
$tr.removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$tr.addClass('selected');
$('#classModal').modal('hide');
let targetValue = $tr.find('td:first').text();
let targetDesc = $tr.find('td:nth-child(3)').text();
$('.id-label').text(targetValue);
$('#label').val(targetValue);
$('.id-labelD').text(targetDesc);
$('#labelD').val(targetDesc);
}
});
});
</script>
Update
After check using DevTools, my input values are getting the right values. Only "label" is being passed to controller. I can't understand why "labelD" isn't.

How to pass textbox value using #Url.Action in ASP.NET MVC Core 2.2

In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>

How to overwrite one model property in ASP.Net core

I have a model with say 10 properties. A, B, C and so on...
Property A is an array.
For each value in array I generate one tag like this:
<div class="col-sm-10 row">
#foreach (var item in Model.A)
{
<div class="col-sm-1 right-buffer">
<i class="" aria-hidden="true">#item.Text</i>
</div>
}
</div>
When user clicks on some link I should redirect it to the same page, but with Some model property changed. For example:
Current url: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=
with model ?name=Alex&age=20&from=fr&CurrentA=
If user clicks on <a> with text foo it should be redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo
then is clicks on <a> with text bar and it should be now redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar
So entire query string (except one parameter) should be preserved to send current model state to server while I want to set one value and redirect it to the same page but with new value.
Eventually, it should acts like postback with one extra value setted to model
Is it possible or I should use JS and perform everything myself?
Manually i solved it like this:
First, create hidden fields for every property in model:
<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
<input asp-for="SessionId" type="hidden" name="sessionId" value="#Model.SessionId" />
<input asp-for="Quantity" type="hidden" name="quantity" value="#Model.Quantity"/>
<input asp-for="SortField" type="hidden" name="sortField" value="#Model.SortField"/>
<input asp-for="IsAscending" type="hidden" name="IsAscending" value="#Model.IsAscending" />
<input asp-for="Offset" type="hidden" name="offset" value="0" />
...
</form>
Then, use JS to replace value in hidden field and then submit form. Values from inputs will be autimatically converter in query string, so everything works fine:
function sortDocuments(sortField) {
var sField = document.getElementById('SortField');
var isDescending = document.getElementById('IsAscending');
if (sField.value === sortField) {
if (isDescending.value.toUpperCase() === 'FALSE') {
isDescending.value = 'TRUE';
} else {
sField.value = 'rank';
isDescending.value = 'FALSE';
}
} else {
sField.value = sortField;
isDescending.value = 'FALSE';
}
document.getElementById('searchForm').submit();
}
Not very elegant, but it does its job.

keeping the data in a form after it has been sent

I have a form that you enter data into and it performs a calculation on it and give an answer. what i want to do is for it to keep the data in the form so that you can quickly repost so that you don't have to change all the data. but I cant keep coming up with the error of it not existing, which I suppose is correct until the form has been posted!
#{
var total = 0m;
var totalMessage = "";
if (IsPost)
{
var age = Request["frmage"].AsInt(0);
var weight = Request["frmweight"].AsDecimal();
var SerCre = Request["frmSerCre"].AsDecimal();
var sexfactor = Request["frmGender"]== "M" ? 1.23m : 1.04m;
total =Convert.ToDecimal ((((140 - age)*weight)* sexfactor )/SerCre ) ;
totalMessage = total.ToString("0.00") + "(ml/min) ";
}
}
<div class="memberRegistration">
<form method="post">
<p>
<label class="formLabel">Age:</label> in years
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
</p>
<p>
<label class="formLabel">Weight:</label> in Kg (1st = 6.35kg)
<input class="formTextField" type="text" name="frmWeight" value="#weight"/>
</p>
<p>
<label class="formLabel">Serum Creatinine:</label> in μmol/L
<input class="formTextField" type="text" name="frmSerCre" value="#SerCre"/>
</p>
<p>
<label class="fieldLabel">Gender:</label>
<select name="frmGender" id="select" value="#sexfactor">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</p>
<p><input type="submit" value="Calculate" /></p>
</form>
<p>Calculated creatinine clearance <b>#totalMessage</b></p>
</div>
Try this
var age = 0;
if (IsPost)
{
age = Request["frmage"].AsInt(0);
}
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
But normally it would be better to use a model to hold your values, then in your controller you pass those values back again to your form
Enable the ViewState of the page and controls and also use aspx control, not HTML.
I don't thing that i realy understand the Question because the default thing is that the web page keeps it's view state so the data will still be the same after the post back but here's the solution :
you can simply use ASP Controls because it keep it's view state
or you can give each control of them it's value in the C# , you can assign to each control it's value back
Hope I Helped
Since you are using ASP.NET MVC Razor, what you can do is, do not submit the form using <input type="submit" value="Calculate" /> , instead change it to a simple button like
<input type="button" value="Calculate" onclick="javascript:Submitform();" />
and submit the form using Jquery POST.e.g. like below
function SubmitForm(){
var formData = $("form").serialize() ;
var submitUrl = 'yourURL' ;
$.ajax({
type : 'POST' ,
url : submitUrl ,
data : formData ,
success : function (data ){ alert ("Request successful") ;}
error : function (jqXHR, status , errorthrown) { alert ("error Occured");}
});
}

MVC: Retrieving form values after submitting

I have a form on a dialog box like so:
<form action="../ControlerFunction">
<input type=text id="id1"/>
<input type=text id="id2"/>
<button type="submit"> OK </button>
<button type="button" class="close"> Cancel </button>
</form>
When the form is submitted it hits my controller function, but how can I retrieve the values of the two text boxes?
Also when I change the form action to:
<form action="JavaScriptFunction();">
or:
<form action="JavaScriptFunction();return false;">
and I have my JavaScript on the same page as:
function JavaScriptFunction()
{
alert("Hi!");
}
it does not hit the function. Am I missing something?
In your controller add another action method that accepts an HTTP POST and takes in the form collection.
Like:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ControllerFunction(FormCollection collection)
Kindness,
Dan
Correct html form tag syntax:
<form method="post" action="/controller/method/" onsubmit="yourJSFunction();">
...
This suits ALL server-side languages and technologies.
Try considering this first:
FORM Tag needs method(POST or GET);
Your INPUT tags don't have name
attributes which will be used for
accessing the values.
Additional code:
<form name="form1" method="POST" onSubmit="JavaScriptFunction(); return false;">
<input type=text id="id1" name="id1"/>
<input type=text id="id2" name="id2"/>
<button type="submit"> OK </button>
<button type="button" class="close"> Cancel </button>
</form>
javascript:
function JavaScriptFunction()
{
var id1Text = document.form1.elements["id1"].value; //get the value of id1
var id2Text = document.form1.elements["id2"].value; //get the value of id2
//do whatever you want here.
}
Further to #Daniel.
You can either use MyAction[FormCollection collection] and then pull your values from the collection object.
Or, if you have a model that you passed to the view you can use TryUpdateModel() to propergate your model with the values from the form.
If you need more then post a comment and I'll add code.
Going home now so there will be a delay as I fight the traffic. :)
Oh, and welcome to SO.
I want to answer your first question.
how can i retreive the values of the two text boxes?
One answer is given by Daniel Elliot.
After giving you input tags a name attribute with the same value of the id attribut, you can access the values as parameters to your action method.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ControllerFunction(String id1, String id2)
Your second question about java script is answerd by Sergei
<form name="form1" method="POST" onSubmit="JavaScriptFunction(); return false;">
<input type=text id="id1" name="id1"/>
<input type=text id="id2" name="id2"/>
<button type="submit"> OK </button>
<button type="button" class="close"> Cancel </button>
</form>
javascript:
function JavaScriptFunction()
{
var id1Text = document.form1.elements["id1"].value; //get the value of id1
var id2Text = document.form1.elements["id2"].value; //get the value of id2
//do whatever you want here.
}

Categories

Resources