mvc - give submit buttons same name when using dynamic value - html

I have a list of items in my view and each has the below submit input type. Each input type has a dynamic value that is then passed through to the parameter 'int button' so the controller is aware of which button has been selected.
View
<input type="submit" name="button" value="#Model.Sites[i].Id" />
Controller
[HttpPost]
public ActionResult ViewInvoice(List<string> invoice, List<int> site, int button = 0)
{
}
The dynamic value is posted correctly to the controller however the buttons are named in the view according to this dynamic value "#Model.Sites[i].Id". How can i set all the button names to "Select" while keeping the dynamic value for my controller?
Thanks in advance.

try using this:
<button type="submit" name="button" value="#Model.Sites[i].Id">Select</button>

the timing will be a little tricky but you can try this
<input type="submit" value="Select" class="btnSubmit1" />
then in your script set a hidden field based on the button click
$(document).ready(function(){
$('.btnSubmit1').on('click', function(){
$('.hdnButton').val('btnSubmit1');
});
});
If the form submits before the field is set then you may need to change the button type to button, set the field and submit the form via ajax Submit a form using jQuery

Related

AngularJS - bind ng-model with button click

I've got an irritating problem with data binding using ng-model and button.
The principle of operation of my site:
My HTML site displays a list of projects (loaded from external .json file).
Each row has a button named Edit which displays a modal containing some <input type="text" filled with relevant data about project (like project.name, project.date etc.)
Initial value of input is equal to object data (text-input called Name will contain project.name etc.)
Object is modified only if you click Save button and confirm the operation (confirm(sometext) is okay).
Closing the modal, not clicking the button or pressing cancel on confirmation box should prevent data from being updated.
Editing input (let's say that project.name is "Project2" and I modify it by adding 3 numbers resulting in "Project2137"), closing modal and opening it again should result in "Project2" text inside input (because object wasn't modified, only input)
So far I understand that single text input should look like this
<input type="text" id="editName" class="form-control" ng-model = "project.name">
Using ng-model means that they are binded. That's what I know. However editing input means that object is updated as soon as I enter some data.
I tried to fiddle with ng-model-options but I didn't find any possible solutions.
I tried to do it programmatically as well using
<input type="text" id="editName" class="form-control" value = {{project.name}}>
....
<button type="button" class="btn pull-right btn-primary btn-md" ng-click="edit(project)" data-dismiss="modal" >Save</button>
And function:
$rootScope.edit = function(project)
{
if(confirm("Are you sure to save changes?"))
{
project.name = angular.element(document.getElementById('editName')).val();
// ...and so on with other properties
This solution is kinda close to what I wanted to achieve (object is updated only on confirm), but I faced another problem: input loads data from object only once at the beginning instead of each time the modal is opened which is against rule #5
Is there any way to fix this using either ng-model bind or custom function? Or maybe there is some other, easier way?
--EDIT--
Here I don't have any problem with saving the data using a button, everything works well and clicking Save is reflected in a projects list. (well until I hit a F5 key).
The problem is that input text is not properly binded to project and that's what I want to fix.
Sample data (pseudocode)
project1.name = "Proj1"
project2.name = "Proj2"
I click an Edit button on row #1
Text input displays "Proj1". Everything is fine.
I change input by adding some random characters like "Proj1pezxde1"
Text input is now "Proj1pezxde1"
I do not click Save button.
I close the modal.
Project summary still displays "Proj1". Okay.
I click an edit button on first row
10. Text input is "Proj1pezxde1" even though I didn't modify an object.
Text input should read data from object again (each time I open this modal) and thus display "Proj1"
That's the problem I want to fix. Sorry for being a little bit inaccurate.
You can create a copy of the project object in modal controller and use this object to bind with the input element of the modal
$scope.copyProj = angular.copy($scope.project);
Assign the copy object properties to project only when save is clicked.
As per my understanding after reading the provided descriptions, you have a list of projects, which is being used as in an repeater and you want to bind each projects data to a Text box and a Button.
Have you tried initializing your Projects object following way?
$scope.projects = [
{ 'name': 'proj1', 'id': '1' },
{ 'name': 'proj2', 'id': '2' }
];
Then you can do something like below to show your data
<div ng-repeat="project in projects">
<div>
<input type="text" class="form-control" ng-model = "project.name">
<button type="button" class="btn pull-right btn-primary btn-md" ng-click="edit(project)" data-dismiss="modal" >Save</button>
</div>
</div>
The simplest way to do this in my opinion is using a second object that is a copy of the project, and after confirmation applying the changes to the original project object.
For example, a simple "pseudo code" of a controller:
function MyCtrl($scope) {
$scope.projects = [...];
$scope.currentProject = null;
$scope.edit = function(project) {
$scope.currentProject = angular.copy(project); // This will create a copy so the changes in $scope.currentProject will not reflect.
// Open dialog with input bound to $scope.currentProject
if (confirm) {
// Assign all properties from currentProject to project
angular.extend(project, $scope.currentProject);
}
}
}
So , as I understand from your question , you need to update the project data only if it is saved. To do that you can maintain a copy of the actual object which get updated only it is saved like below :
Here we are using angular.copy(), which does a deep copy of the source object.
$scope.original = {name : "xyz"};
$scope.project = angular.copy(original);
//Call this when the user confirms to save , here we are replacing the
//original copy with the latest object that needs to be saved.
$scope.save = function () {
$scope.original = angular.copy($scope.project);
}
//Call this when closing the modal or clicking cancel or when losing
//focus, this will reset the changes to the original copy.
$scope.reset = function () {
$scope.project = angular.copy(original);
}

Angular 2 html form validation

I've created a form using html validations with Angular 2.
I want to to check the sate of the inputs (no empty, correct format, etc) when the user click to a certain button. At the moment I'm doing it as following:
<form id="memberForm" #memberForm="ngForm" >
<input
type="text"
id="MemberName"
required
name="MemberName"
[(ngModel)]="newMember.name">
</form>
<div
[ngClass]="{'button_disabledButton' : !memberForm?.valid}"
(click)="onSubmit(memberForm?.valid, memberForm);">
<span>Next</span>
</div>
With this, I'm only evaluating the input once clicked and focus out. How can I make it hapens when the user click in the "Next" element?
You should make getter/setter solution for your ngModel input.
In the .ts file in the appropriate class put this:
savedVar:string = '';
get variable(): string {
return this.savedVar;
}
set variable(str: string) {
this.savedVar = str;
// do your validation
}
In template use ngModel=variable like this:
<input [(ngModel)]="variable">

Button value is not posted to Controller while Form Submit?

In my View, there are two <input type="image"> tags, and they are inside a Form.
In my Controller, the value of these two <input type="image"> always appears as 'null'. Earlier, with <input type="submit">, the values were posted to the controller.Now they're not.Can anyone tell me how to access those values in the Controller?
View:
#using (Html.BeginForm("Load", "Consent"))
{
//some code
<div id="button1" style="right:150px; width:90px; bottom :15px;position:absolute"><input type="image" src="../../img/ButtonBack.png" name="button" value="Previous" id="back" /></div>
<div id="button2" style="right:20px; width:90px; bottom :15px; position:absolute"><input type="image" src="../../img/ButtonNext.png" name="button" value="Acknowledge" id="ack" /></div>
</div>
}
The Form is getting posted to the controller, but the value of string button is 'null'
Controller:
[HttpPost]
public ActionResult Load(bool? chk_acknowledge, string button)
{
// some code
}
The browser is not required to post the value of the "value" attribute, so don't rely on it. Value is meant for radio and checkbox input fields: http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT
However, browsers will post two other form fields: name.x and name.y. You could instead name your two image buttons "nextButton" and "prevButton". In your action, check if Request.Form contains "nextButton.x". If it exists, nextButton has been pressed. Likewise, if "prevButton.x" exists, prevButton has been pressed.
Only the value of the clicked image button would be posted (only the clicked submit button). While having the 2 image buttons inside a form, if there is another submit button and you click on that, the image buttons would not get posted.
Eg : You click on first image button inside div#button1 - in the post array, there would be [button] => Previous the other image button will not get posted.
Quote from the specification:
When a pointing device is used to click on the image, the form is
submitted and the click coordinates passed to the server. The x value
is measured in pixels from the left of the image, and the y value in
pixels from the top of the image. The submitted data includes
name.x=x-value and name.y=y-value where "name" is the value of the
name attribute, and x-value and y-value are the x and y coordinate
values, respectively.
So:
#using (Html.BeginForm("Load", "Consent"))
{
... some code
<input type="image" src="#Url.Content("~/img/ButtonBack.png")" name="Previous" />
<input type="image" src="#Url.Content("~/img/ButtonNext.png")" name="Acknowledge" />
}
and then:
[HttpPost]
public ActionResult Load(bool? chk_acknowledge)
{
if (!string.IsNullOrEmpty(Request["previous.x"]))
{
// the Previous image button was clicked
}
else if (!string.IsNullOrEmpty(Request["acknowledge.x"]))
{
// the Acknowledge image button was clicked
}
...
}

How can I pass a parameter via submit button?

In my code for an mini online book store i have a following line repeating 5 times with different value for 'name' parameter
<input name="JSP-2" type="submit" value="Buy">
On clicking the button Buy, the application redirects to a file buy.jsp where it gets the value of name and displays corresponding details of the book.
In my buy.jsp, I have included
<% String bname= request.getParameter("name");
out.print(bname);
%>
But the name doesnt get assigned to bname and it shows the value as null. How do I pass a parameter from the submit type input?
Please help.
You have to pass the parameter in the request.
Since you are having a form, and submitting the form, you can have a hidden field in the form called, say "submitType", and populate it whenever you click the button, using javascript. Then this will be available in the next request.
Somewhere inside the form :
<input type="hidden" name="submitType">
in the submit buttons:
<input name="JSP-2" type="submit" onclick="setType('Buy')">
Javascript:
formName is the name of your form
<script>
function setType(type)
{
//formName is the name of your form, submitType is the name of the submit button.
document.forms["formName"].elements["submitType"].value = type;
//Alternately, you can access the button by its Id
document.getElementById("submitId").value = type;
}
</script>

Using 2 buttons in same ASP.NET MVC Form

In general, is it possible to have two different buttons within the same form that post to different controller actions in ASP.NET MVC?
I am essentially trying to have two input (type="button") tags in the same form, but I want them to perform different controller actions. I would like to do this in a few cases because I think it provides a good aesthetic to be able to click buttons as opposed to hyperlinks. Is there a way to do this or should I design it differently?
Not really possible without using Javascript. With Javascript you'd just have to define different click handlers that invoked the proper action.
$(function() {
$('#button1').click( function() {
$(form).attr( 'action', '<% Url.Action( "action1" ) %>' )
.submit();
return false; // prevent default submission
});
$('#button2').click( function() {
$(form).attr( 'action', '<% Url.Action( "action2" ) %>' )
.submit();
return false; // prevent default submission
});
});
Some thoughts about handling this in the browser:
You can use links which are styled to look like buttons. This is easy to do, either with images or by putting the link in a block element with borders.
You can use two buttons which don't directly submit; they instead call a javascript function that sets the form action before submitting.
If all you want is something like OK & Cancel buttons, then have a look at this post by David Findley.
I'm using this method on my Edit view, where I have an Edit button and a Delete button. The delete button only requires the Id of the item. In the code below you can see that I've named my attribute "AcceptFormValueAttribute". This is method good for me, because my Delete [Get] action just shows a message asking for confirmation, so needs the redirect.
[ActionName("Edit")]
[AcceptFormValue(Name = "Action", Value = "Delete")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult EditDelete(int? id)
{
return RedirectToAction("Delete", new { id = id });
}
This has nothing to do with ASP.NET MVC but with html. The only way I see how you could do this is by modifying the action attribute of the form tag using javascript on submission of the form by checking which button was pressed.
Well there are a few ways you could handle this. Assuming you aren't sending data with the button click I'd go with option 3. If data must be included then consider option 1 with some sort of temporary data store (like TempData).
One form posts to one controller
action on submit and the controller
action checks which button was
clicked and then dispatches a
RedirectToAction(). (Not great)
Multiple forms on one page post to multiple controller actions (Better)
Inside or outside a form create an input type="button" and give it an onclick handler
that redirects the user to a controller action (Best)
Haven't tried this, but given the ID of the clicked button does get sent VIA http POST, you could probably do something like:
<input type="submit" name="GO" ID="GO" value="GO BUTTON" />
<input type="submit" name="STOP" ID="STOP" value="STOP BUTTON" />
Then on the mvc end, just have two methods, one with a go parameter, one with a stop parameter.
Method #1
How about using two different forms wrapping the buttons, then using CSS to position one of them so that it appears (visually) to be inside the "main" form?
A really quick example:
<fieldset id="CombinedForm">
<form ... action="Method1">
...form stuff here...
<input id="Button1" type="submit" value="Do something">
</form>
<form ... action="Method2">
...form stuff here...
<input id="Button2" type="submit" value="Do something else">
</form>
</fieldset>
...Then using CSS as follows:
#CombinedForm {
position: relative;
padding-bottom: 2em; /* leave space for buttons */
}
#Button1, #Button2 {
position: absolute;
bottom: 0;
}
#Button1 {
left: 0;
}
#Button2 {
right: 0;
}
The result should be that you have a fieldset or div which looks like a form, having two actual HTML forms inside it, and two buttons which are positioned within the parent box, yet submitting to different locations.
Method #2
Another method occurs: have both buttons in the same form, pointing to one controller action, that then decides (based on the value of the button clicked) which action to redirect to.
Its not Javascript required...
how about this
public ActionResult DoSomething()
{
// Some business logic
TempData["PostedFormValues"] = Request.Form;
if (Request.Form("ButtonA") != null)
{
return RedirectToAction("ActionA", RouteData.Values);
}
return RedirectToAction("ActionB", RouteData.Values);
}
I think that I can suggest more simple one.
For example you have two buttons : ButtonA,ButtonB and want to perform different
action on each one.
Simplest solution is : just use BeginForm statement:
#using ( Html.BeginForm("ButtonA" , "Home") )
{
<input type="submit" value="ButtonA"/>
}
#using ( Html.BeginForm("ButtonB" , "Home") )
{
<input type="submit" value="ButtonB" />
}
You must also declare ButtonA,ButtonB actions in your Home controller :
[HttpPost]
public ActionResult ButtonA()
{ . . . }
[HttpPost]
public ActionResult ButtonB()
{ . . . }