how to search with GET method in MVC - c#

I am trying to do a search with GET Method but I couldnt do the way I need. My html-css code is like below
<div class="top_search_form">
<a class="top_search_btn" href="javascript:void(0);" ><i class="fa fa-search"></i></a>
<form method="GET" action="/Banyo/Urunler">
<input type="text" name="search" value="Search" onFocus="if (this.value == 'Search') this.value = '';" onBlur="if (this.value == '') this.value = 'Search';" />
</form>
</div>
It looks like below
The user enters some text and hit the enter to do a search. But when I do a search, the URL is like below, which is not the way I need.
/Banyo/Urunler?search=asd
when the user hits the enter. I want to see the link below
/Banyo/Urunler/asd
how can I have this URL "/Banyo/Urunler/asd" ? what should I do to have this?
My MapRoute is like below
routes.MapRoute(
"Urunler", // name it!
"Banyo/Urunler/{Filtre}", // Route name
new { controller = "Banyo", action = "Urunler", Filtre = UrlParameter.Optional } // Parameter defaults
);
and I updated my html
<form method="GET" action="/Banyo/Urunler">

if the parameter name in your action (search in this case) is not defined in your route config, it'll be appended as a query string parameter when doing GET requests.
the default route defines an id parameter so you could use this instead.
Your search field would be renamed to id and your action would have an id parameter as well.
public ActionResult Urunler(string id)
{
}
Another option would be to use attribue routing (if you are using MVC4 and above).
Route("Banyo/Urunler/{search}")]
public ActionResult Urunler(string search)
{
}
Attribute routing in MVC4 would require you to install the nuget packages yourself ... i think they are added by default in MVC5

In the form, add JavaScript to the onsubmit attribute. For example...
<form onsubmit="location.assign(this.action+'/'+this.search.value);return false" action="/Banyo/Urunler">
This browses the <input> tag's value appended to the URL provided by the form. this.search provides access to the <input> element with the name of "search".

Related

Issue with Attribute Routing working with traditional form parameter

I am having trouble with using attribute routing in ASP.NET MVC 5. Here is the action im using in my controller:
[HttpGet,Route("Home/ChangeID/{MovieInput}")]
public ActionResult ChangeID(int MovieInput)
{
return View();
}
Here is the form I am using to send the parameter to this action:
<form method="get" action="#Url.Action("ChangeID", "Home")">
<label for="movieInput">Change an ID: </label>
<input type="text" id="MovieInput" name="MovieInput" placeholder="Enter Your ID" />
<input type="submit" />
</form>
The route works perfectly with a URL such as
/Home/ChangeID/65
however it does not support the form submission parameter typing where its
/Home/ChangeID?MovieInput=65`.
How can I change the form submission to meet the latter or is there a way to change the route to satisfy a parameter typed this way?
`
If you change route template to Route("Home/ChangeID")
//GET /Home/ChangeID?MovieInput=65`
[HttpGet,Route("Home/ChangeID")]
public ActionResult ChangeID(int MovieInput) {
return View();
}
it will work for the form action or make the route parameter optional Route("Home/ChangeID/{MovieInput?}") (note the ?)
//GET /Home/ChangeID/65`
//GET /Home/ChangeID?MovieInput=65`
[HttpGet,Route("Home/ChangeID/{MovieInput?}")]
public ActionResult ChangeID(int MovieInput) {
return View();
}
it should have the same effect.
The advantage of the second option over the first is that it will allow both /Home/ChangeID/65 and /Home/ChangeID?MovieInput=65 to match the controller action.

MVC, how to post data to controller and redirect to aspx page

I have an MVC view where user can set a flag and post data to controller (post because I want to hidden query string)
After the controller have done his job I want to redirect to website home page that is an aspx page (my site is mixed aspx and MVC)
Is there a way to do that?
This is my view
#model MessaggiVM
<form role="form" class="form-inline" method="post" action="Messaggi/VaiAllaHome">
<button id="btnHome">Vai alla pagina iniziale</button>
<div class="form-group">
<label for="nascondi">hiding</label>
<input id="nascondi" type="checkbox" name="nascondi" value="true" />
</div>
<input type="hidden" name="elencoPost" value="#Model.Posts" />
#*#Html.ActionLink("Messaggi", "VaiAllaHome", new { posts = Model.Posts} )*#
</form>
And this the controller
[HttpPost]
public RedirectResult VaiAllaHome(bool? nascondi = false, IEnumerable<Messaggio> elencoPost = null)
{
// do something
return Redirect(Url.Content("~/"));
}
When I run this code controller action is executed without error but redirect is not done and browser remain on the view
Other problem is that elencoPost parameter is empty in the action but I'm investigating it
EDIT
Honestly I'm thinking to post data on input change and switch button for a simply link
EDIT 2:
found the reason: in default.aspx i have a auto-redirect to Message page :(
Try
return Redirect("~/home.aspx");
or
return Redirect(Url.Content("~/home.aspx")
You should be able to use Redirect with a relative url:
[HttpPost]
public RedirectResult VaiAllaHome(bool? nascondi = false, IEnumerable<Messaggio> elencoPost = null)
{
// do something
return Redirect("/home.aspx");
}
Try using a #Url.Content on your form tag
<form action="#Url.Content("~/Messaggi/VaiAllaHome/")">
Then in your Controller
[HttpPost]
public RedirectResult VaiAllaHome(bool? nascondi = false, IEnumerable<Messaggio> elencoPost = null)
{
// do something
return View(Url.Content("~/"));
//return RedirectToAction("Action", "Controller", new { routeParameter = value } /*e.g. "id = 1"*/);
}

Hide parameter value from URL

I have a URL like this
http://localhost/PW/LeaveWithoutPay/Edit?id=9
and I want to hide the id?=9 from my URL. Can any one demonstrate how to hide this id parameter with an example? I am using Visual Studio 2012.
You must need to implement Post method instead of GET method. Here is a sample example for it.
In your controller define something like this
public ActionResult Edit([FromBody] int id) {
TempData["MsgText"] = id.ToString();
return RedirectToAction("Index");
}
Now in your view, implement the POST method. A sample example is:
#{string id =(string)TempData["MsgText"];}
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "frmCallThis" })){
#Html.Label("label",string.IsNullOrEmpty(id)?"No Id Provided":"Current ID = " + id)
#Html.TextBox("id");
<input type="submit" value="Get This Printed" />
}
Finally you have the following output: (Before Submit)
And After submit:
Hope this helps,
Only one thing you have to doing here is using POST, not GET method. Because the web request is usually stateless, so I don't think we have any other methods to hide your id.

html form posting to mvc controller

I am trying to set up a simple login html page, whose action is sent to mvc controller on another of my sites. I have no problem setting up the page to do the post, and in the mvc controller I have my method that reads the form post. The problem is that I am not seeing my fields from the html form in the form collection.
Is there something special that I need to do to read a form post within a mvc controller method, if so what is that?
The is the form action markup from my page
<form action="http://reconciliation-local.sidw.com/login/launch" method="post">
User Name <input type="text" id="username"/><br/>
Password <input type="text" id="password"/>
<input type="submit" value="launch"/>
</form>
The controller method
[HttpPost]
public ActionResult launch(FormCollection fc)
{
foreach (string fd in fc)
{
ViewData[fd] = fc[fd];
}
return View();
}
When I step through the controller method code, I am not seeing anything in the formcollection parameter.
Post Html To MVC Controller
Create HTML page with form (don't forget to reference a Jquery.js)
<form id="myform" action="rec/recieveData" method="post">
User Name <input type="text" id="username" name="UserName" /><br />
Password <input type="text" id="password" name="Password"/>
<input type="submit" id="btn1" value="send" />
</form>
<script>
$(document).ready(function () {
//get button by ID
$('#btn1').submit(function () {
//call a function with parameters
$.ajax({
url: 'rec/recieveData', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
timeout: '12000', (optional 12 seconds)
datatype: 'text',
data: {
//Get the input from Document Object Model
//by their ID
username: myform.username.value,
password: myform.password.value,
}
});
});
});
</script>
Then in The MVC Controller
controller/action
| |
1. Create Controller named rec (rec/recieveData)
Create View named rec.cshtml
Here is the controller:
public class recController : Controller
{
// GET: rec
string firstname = "";
string lastname = "";
List<string> myList = new List<string>();
public ActionResult recieveData(FormCollection fc)
{
//Recieve a posted form's values from parameter fc
firstname = fc[0].ToString(); //user
lastname = fc[1].ToString(); //pass
//optional: add these values to List
myList.Add(firstname);
myList.Add(lastname);
//Importan:
//These 2 values will be return with the below view
//using ViewData[""]object...
ViewData["Username"] = myList[0];
ViewData["Password"] = myList[1];
//let's Invoke view named rec.cshtml
// Optionaly we will pass myList to the view
// as object-model parameter, it will still work without it thought
return View("rec",myList);
}
}
Here is the View:
#{
ViewBag.Title = "rec";
}
<h2>Hello from server</h2>
<div>
#ViewData["Username"]<br /> <!--will display a username-->
#ViewData["Password"] <!-- will display a password-->
</div>
If you posted some code it would be much easier to help you, so please edit your question...
Make sure that your form's action has the correct address, that your method is specifying POST (method="POST") and that the input fields under your form have name attributes specified.
On the server side, try making your only parameter a FormCollection and test that the fields in your form posted through the debugger. Perhaps your model binding isn't correct and the FormCollection will at least show you what got posted, if anything.
These are just common issues I've seen. Your problem could be different, but we need to see what you're working with to be able to tell.
Try something like this:
cQuery _aRec = new cQuery();
_aRec.Sqlstring = "SELECT * FROM Admins";
DataSet aDS = _aRec.SelectStatement();
DataTable aDT = aDS.Tables[0];
foreach (DataRow aDR in aDT.Rows){
if (txtAdminUsername.Text == aDR[0].ToString()){
if (txtAdminPassword.Text == aDR[1].ToString()){
Session["adminId"] = aDR[0];
Response.Redirect("Admin.aspx");
return;
}
}
}
Make sure that your FormCollection object properties for username and password are defined properly.
I had to use the name attribute on the text tag, and that solved my problem, is now working like a charm.
You have to use Ajax to do that.. Whenever you want to "submit" from client side, you should use Ajax to update the server
Step 1 - you redirect your Ajax call to your action, but with your list of parameters in the query-string appended
$.ajax(url: url + "?" + your_query_string_parameter_list_you_want_to_pass)
Step 2 - add optional parameters to your Controller-action with the same names and types you expect to get returned by the client
public ActionResult MyControllerAjaxResponseMethod(type1 para1 = null,
type2 para2 = null,
type3 para3 = null, ..)
Know that the optional parameters have to be initialized, otherwise the Action itself will always ask for those
Here's where the "magic" happens though --> MVC will automatically convert the query-string parameters into your optional controller-parameters if they match by name
I was also looking for a good answer for this, --> i.e. - one that doesn't use q-s for that usage, but couldn't find one..
Kinda makes sense you can't do it in any other way except by the url though..

Controller methods when submitting an AJAX request

I have an MVC project that has a page with several forms on it. Most of the content on the page is rendered based on an initial form that a user submits. When a user updates information on that page I don't want the entire page to refresh I just need it to submit the form and stay on the page. I've tried to setup the form to submit with AJAX, but I don't know what to make the controller method return to accomplish this.
Form:
<div id="HeatNameDiv" title="Change Heat Name">
#using (Ajax.BeginForm("ChangeHeatName", "Home", new AjaxOptions(){UpdateTargetId = "HeatNameDiv"}))
{
<section>
Heat Name:<input type="text" name="heatName" value="#Html.ValueFor(x => x.heatname)" style ="width:100px"/>
Change to:<input type="text" name="updatedHeat" value="" style="width: 100px" />
<input type="submit" name="ChangeHeatName" value="Change" />
</section>
}
Current Controller:
public ActionResult ChangeHeatName(string heatName, string updatedHeat)
{
string user = User.Identity.Name;
HomeModel H = new HomeModel();
H.ChangeHeatName(heatName, updatedHeat, user);
return Content("Index");
}
It depends on what you want refreshed. Ajax.BeginForm expects an HTML fragment. So you need a partial that represents the heatNameDiv that you want to replace after submit:
public ActionResult ChangeHeatName(string heatName, string updatedHeat)
{
string user = User.Identity.Name;
HomeModel H = new HomeModel();
H.ChangeHeatName(heatName, updatedHeat, user);
return PartialView("NameOfPartialView", H);
}
I agree with Jeremy because Ajax.BeginForm is less flexible. I have tried hard to use it in the past, but the fact that it replaces the target element, instead of the innerHtml of the target, makes it difficult for many scenarios.
With $.ajax you can set url: '#(Url.Action("MyActionReturningAPartialView"))' and in the .success callback function(response) { $('#heatNameDiv').innerHtml(response); }
The action you call still returns a PartialView.

Categories