Adding a post outside of a form - asp.net-mvc

I have a form in my razor view which works exactly as it should. I select values from the drop down and press the submit button and it return to me a paginated set of results. All well and good.
#using (Html.BeginForm())
{
int index = 0;
foreach (var type in #Model.AttributeTypes)
{
#Html.DropDownListFor(m => m.SelectedAttributeValueIds[index], Model.AttributeValuesList[Convert.ToInt32(#type.Value)], "Filter by " + type.Text)
index++;
}
<input type="submit" value="Filter"/>
}
The problem is that at the bottom of the page, outside of the form I want a Show all button/link. Pressing this button should essentially do the same thing that the above submit button does. In other words I'd like this Show all button to show all of the results of the last query (or the currently selected values in the dropdowns - not too bothered which) without pagination. I can do the no pagination bit, that is easy. What I want to know is how will my button/link get the values from the dropdown from outside of the form and submit that form?

You can use javascript/jquery to submit the form on click of that button.
$('#formId').submit();
To wire this up you could do the following on your document ready script:
$('#buttonId').click(function() {
$('#formId').submit();
});

Use javascript to read information on the dom element you need to grab the info and them submit an ajax request.

Related

Rails count number of checkboxes in a view before posting

I have little knowledge of Javascript, but I think it might be the only way to make things work in my problem.
I am using rails 5.
I basically have checkboxes in a view that represent a price, and every time I check or uncheck one, I would like to update the total price for that view (that I then pass in a hidden_field and a post request).
I'm guessing that what I have to do is get an onclick event going everytime I check or uncheck a box, and update a variable that I then show in the view.
I've found something that looks very similar to my case, but unfortunately I'm unable to reproduce it: Rails Jquery compute total from selected checkboxes in a table
I have my checkboxes with a class "checkbox-count", and I can send an alert everytime I check them, but that's about all I have so far...
Your help would be very appreciated!
This could be handled on the server side by getting an array(checkbox names are all the same array value) of the checked boxes values in a controller action and adding the values together there, maybe you have a reason not to though?
Otherwise this is more of a javascript question, but it could be handled with some vanilla javascript like this maybe:
// a quick custom function for calculating total values of all checked checkboxes in a given form
function calcFormCheckedBoxesTotal(form) {
total = 0;
form.querySelectorAll("input[type='checkbox']:checked").forEach(checked_box => {
total += parseInt(checked_box.getAttribute("value"));
});
return total;
}
// get all form checkbox inputs to be used
checkboxes = document.querySelectorAll("form input.checkbox-count");
// loop through all given form checkbox inputs so we can...
checkboxes.forEach(checkbox => {
// ... add click event listener to each checkbox
checkbox.addEventListener('click', event => {
// ... use my custom function to calculate totals of all checked boxes in the parent form of currently clicked on checkbox and store in "total" variable
total = calcFormCheckedBoxesTotal(event.target.parentElement);
// ... change value of my text input with id="total_price" to show total of checked boxes. Change the target of the querySelector to whatever you want to update(your hidden field) with the total.
document.querySelector("#total_price").value = total;
});
});
<form>
<input type="checkbox" class="checkbox-count" name="price[]" value="25"><label>$25</label><br>
<input type="checkbox" class="checkbox-count" name="price[]" value="50"><label>$50</label><br>
<input type="checkbox" class="checkbox-count" name="price[]" value="100"><label>$100</label><br>
<input type="text" id="total_price" name="total_price" value="0">
</form>

how to pass the multiple values from one view to another view using session mvc

In my first page, i have list of amounts column related to that plan. if i click one column it redirects to the another page.. In that page, i want to show the amount what i click before. I never used session before. Now i tried. but it is always showing single amount only.. i don't know how to create session for multiple values..
controller
Session["rs360"] = "Rs. 360";
Session["rs1000"] = "Rs. 1000";
Session["rs1500"] = "Rs. 1500";
View
<div><%:Session["rs360"] %></div>
Actual view(Index.Cshtml)
<div id="rs360">
<span class="font18">Rs.360</span>
</div>
<img src="../../Content/Images/Subscribe now on click.png" class="btn" onclick="return sms_confirm1()" />
<div id="rs1000">
<span class="font18">Rs.1000</span>
</div>
<img src="../../Content/Images/Subscribe now on click.png" class="btn" onclick="return sms_confirm1()" />
when click the button it goes to another view called Payment
<td>
<a class="callpickupcash" href="<%: Url.Action("ElectronicTransfer", "Home") %>"><img src="/Content/Images/ebanking.png" class="Featured-plan"></a>
</td>
when click this above button it will open one popup menu... At that menu i should show the amount value..
Here Only i passed the following session what i already declare at top
<div><%:Session["rs360"] %></div>
Here i gave the session variable so my result is showing 360. but when i click 1000 it should change.. How to do this?
I found the answer to my question by using localStorage() function..
I passed the radiobuttons for values like
<%:html.radiobutton("smscount",500,true)%>
Jquery
<script type="text/javascript">
function sms_confirm() {
var amount = $("input:radio[name=smscount]:checked").val();
localStorage.setItem("smscount", amount);
if (r == false) {
return false;
}
}
Redirect page
Here I am showing the values into the textbox. so i take the textbox id..
$(function () {
var textbox = $('#Amount');
var checkValue = localStorage.getItem("smscount")
textbox.val(checkValue);
});
If you are not using session for anything else, I suggest to you that for this problem you don't need session. You can simply pass the clicked amount to the action method that you are calling with that link, and then incorporate that amount back into the model you are passing to the second view. You can do that by using viewData or even better by having the view strongly typed to a view model that contains that information.
Edit
OK. Let me see if I got this right. The link on the first view that is rendered with:
Url.Action("Payment", "EmployerVas")
Calls a Payment method in EmployerVas that renders a view (view2) that contains a button rendered with:
Url.Action("ElectronicTransfer", "EmployerVas","Employer")
That will open up a popup menu and you want the value clicked on in the first view to show up in the popup. If that is what you are trying to do and without changing too much in what you are doing and moving you to a viewModel based system, I would change the following:
Url.Action("Payment", "EmployerVas", new{amount="360"})
Change the Payment method in the EmployerVas controller to accept an input parameter of type int or long or whatever meets your needs.
Then you can either store that in the session if you need to and pass it to view2 and then in view2 change the link again to pass that value (or if you want to use the value stored in the session then leave link as is):
Url.Action("ElectronicTransfer", EmployerVas","amountToSHow=sessionOrViewDataPassedValue")
Now since the value is in the session you can use it or you can change the ElectronicTransfer method to accept an input value of the same type as above and named amountToShow then you can pass it to the popup.

How to determine value of text box in ASP MVC view

Is it possible to access the value of a text box within the same View? For example, in my view I have the following text box
#Html.TextBox("searchValue", ViewBag.CurrentFilter as string, new { placeholder = "Search" })
If a user enters a value, then hits submit, the page will send that search criteria to the controller, query the database based on the criteria, and then display the results back in the view. When the view is rendered again, the text stays in the search box and the tag is rendered
<input id="searchValue" name="searchValue" placeholder="Search" type="text" value="what i just typed in here" />
is there a way for an ASP MVC 3 view to access the value of that text box? I want to create a condition similar to
#if (searchValue.hasValue())
{
do something in here
}
The view is rendered synchronously, when the page first loads. All Razor expressions are evaluated when the page renders, so what you get back is static HTML. You can't use that to track subsequent changes to form values - only to carry out logic based on their initial values for the current response.
You need to use Javascript. Supposing you have a link with an id of myLink. Style it to display:none; by default. Then, with jQuery, you can do the following:
<input id="searchValue" name="searchValue" ... />
<script type="text/javascript">
$('#searchValue').change(function (){
if($('#searchValue').val().length > 0) {
$('#myLink').show();
} else {
$('#myLink').hide();
}
});
</script>
If you need more complex logic, you could switch out the link with a partial view and update it with AJAX calls.
Maybe I misunderstood, but it looks like you are populating the searchbox with ViewBag.CurrentFilter and then "When the view is rendered again, the text stays in the search box" as "value="what i just typed in here"
Which sounds to me like you already know what the search text is, so why do you need to read the value of the textbox? Why wouldn't the logic be
#if (`ViewBag.CurrentFilter` hasSomeValue)
{
do something in here
}
Sorry in advance if I missed the point.

How do I implement Multiple Submit Buttons for a multi-row form?

I have a form that will have this format:
I am first row (textbox) [Submit Button]
I am second row (radiobutton) [Submit Button]
I am third row (checkbox) [Submit Button]
I am fourth row (dropdown) [Submit Button]
I am fifth row (textbox) [Submit Button]
I am sixth row (textbox) [Submit Button]
I am seventh row (radiobutton) [Submit Button]
The text (ex: I am fourth row) and the value of the control will be loaded from a database. I would like the Submit button to only send the value of its control (ex: row 4, dropdown value == N/A) to the server. Not all the controls' values.
Now will I have to wrap each row with a Html.BeginForm or can I wrap all rows with one Html.BeginForm? What would be the best (or even better) way to handle such a thing.
Note: I've searched around SO and haven't seen a problem like this discussed.
Sounds like you need to create a loop to build your table.. and conditionally create the rows based on whatever it is that you are keying on to decide to put a specific element type( text, radio, checkbox, etc..) and each row would be have to be wrapped in form tags. Since you would need to evaluate for the correct element, you can use that to also build your BeginForm to tell it where to post to an action, possibly a different action per element type so that the action receives only the data you want it to receive
I believe you can do this using Jquery:
First of all create individual forms for each row.
Try using below code..
Jquery:
function SubmitForm(btn)
{
var form = btn.serialize();
$.post("your URL here",form,function() {
alert("Saved");
});
}
Html:
<form id='form1' >
...
Other controls on your form
...
<input type="button" id="form1" onclick="SubmitForm(this)" />
</form>
First off, you cannot nest form tags (browsers don't support it).
An input[type=submit] on click triggers a post back event on its' parent form.
ex.
<form action='/PostBackTo' onsubmit='DoSomething()'>
<input type='submit />
</form>
So you will have to wrap every control inside its own form and any additional data you want posted back will need to reside in input or select tags inside the form.
Say you would like to post back an id with every submit, you would have to add
<input type='hidden' value='#id' />
inside every form tag to have it included in the postback.
I'd suggest if you do it this way, use javascript to intercept the submit action and submit the forms' data via AJAX post (if it's something like a 'save changes' button).
For example: 1. I am first row:
<input type="text" value="#textValue" id="txtFirstRow" />
<input type="button" onclick="post('txtFirstRow');" />
Javascript code:
function post(name)
{
var txt = document.getElementById(name).value;
$.getJSON("/Controller/Action",
{
text: txt
},
function (data) {
//returned result
});
}

How to post values outside a partial view to controller in ASP.NET MVC?

I am working with a paginated list like in the NerdDinner sample.
I am trying to show the navigation buttons for forward and back. I want there to be a form post
when these are clicked so that the search text is still passed in.
The problem is, the search text is stored in a form that is outside the partial view that the paged list is in and so the controller never finds it.
Any ideas on what I'm missing?
You could consider passing not only query results but also the search text to partial view via view model.
You can include
<input type="hidden" id="search" />
in the form with navigation buttons and fill it on POST using jQuery:
$(document).ready(function() {
$('.yourNavButtonsClass').click(function () {
var searchText = $('input#yourSearchTextBoxId').val();
$('input#search').val(searchText);
});
});
Unfortunately my solution requires Javascript/jQuery.
google appends search text to the url, yahoo and msn too. I'm sure you can do the same and this is the better way :)

Resources