How to determine value of text box in ASP MVC view - asp.net-mvc

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.

Related

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.

Adding a post outside of a form

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.

how to call controller from button click without using ajax mvc

I'm new to web programming in general so this is probably a really simple question. I couldn't find anything on the web however.
What I want to do is call my controller with the typed search string and return the results from a database and paginate the results. Right now I am using a function that is called when the button is pressed. The function looks like so:
function SubmitSearch() {
var searchBox = document.getElementById('searchBox');
var searchButton = document.getElementById('SearchButton');
$.post("MyController/MyAction/",
{
searchString: searchBox.value,
page: null
}, function(result) {
$('#searchResults').html(result);
searchButton.value = "Search";
});
}
What happens is my controller is called, and my searchResults div is populated with the results and paginated. The user can click any search result returned to view the details.
The problem is when the user clicks the browsers 'back' button, the page returns to the state before the search was entered, and this is because of the ajax call. What I want to do is, call the controller and have the page load like google would. Instead of using a PartialView, I would use a View (my guess).
How would I call the controller and have the page RELOAD with the results. I must be missing something fundamental because this definitely seems like it should be easy.
If you don't want to use AJAX then you need to place your text field in a form element on your page, something like:
<form action="MyController/MyAction/" method="get">
<input id="SearchBox" name="SearchBox" type="text" />
<button type="submit">Search</button>
</form>
Then in your controller return the view with the list of results.
You probably also want to look into RESTful URLs and the PRG (Post, Redirect, Get) pattern to maintain the integrity of the back button and enable correct bookmarking of pages etc.
I think you might actually be looking for an AJAX History library to help when the Back button is pressed rather than altering your app. Take a look at this blog post.
Aspx:
<% using (Html.BeginForm<MyController>(m => m.MyAction(null)) { %>
<%= Html.TextBox("q"); %>
<% } %>
// Listing
Controller:
public class MyController : Controller
{
public ActionResult MyAction(string q)
{
var repository; // instance of your repository.
if (String.IsNullOrEmpty(q))
{
return View(repository.GetAllBlogs());
}
return View(repository.SearchBlogs(q));
}
}

ASP.NET MVC - Build Search Results into a Div

I'm new to ASP.NET MVC, but I need to perform a search for articles that match a selected category. The results of this query need to be written into a "search results" div overlay with DHTML- jquery, probably.
So, I need the results of an Action, but not to render a view. I was thinking I could use Json and then iterate over the resulting records, somehow.
Or is it easier to use RenderPartial... but how would I use this in this DHTML scenario?
Thanks.
I like the way Steve Sanderson describes in his ASP.NET MVC book. It dosnt work with JSON, but returns a partial. This makes it easier to have both: An Ajax and a non-Ajax version.
The cotroller returns a View or Partial depending on the type of request:
public ActionResult GetArticles(string category)
{
...
if(Request.IsAjaxRequest())
{
return PartialView("ArticleListPartial",articleModel)
}
else
{
return View("ArticleListPage",articleModel)
}
}
The search by default submits the from with with a Non-Ajax post:
<form id="articleSearch" method ="post" action="/Article/GetArticles" >
...
<input type="submit" value="Get the articles!" />
<form>
Then there is a Jquery snippet that kicks in when Javascript is available and submits the request via Ajax
<script language="javascript" >
$(function() {
$("#articleSearch").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(modelResponse) {
("#articleResultContainer").html(modelResponse);
});
return false;
});
});
</script>
Hmmm, sounds like you are trying to do a filter?
If this is the case I think it's a bad idea trying to search within your html. I think a better approach would be to post back using jQuery, get your result set from whatever database you are using, and return that back to the view as apartial view.
When you are searching your database you should apply the filter at that point using sql, Linq2Sql or whatever you're using.
If you are still Hell bent on searching the HTML then I'd give each relevant div a class name of say class="DivSearchable". Then in jQuery you can do something like;
$('.DivSearchable").each(function() {
var text = $(this).val();
"Now test text for contents of your seach string"
if (BoolIfFound == true)
$(this).addClass("highlightClassName");
});
highlightClassName would set the background-color to something so you can see which divs contains the search string.
make sense?

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