<form method="post" class="search-form" action="?">
<fieldset>
<input class="search home_input_search" placeholder="Поиск" type="search" />
<input type="submit" class="subm but_search" value="" />
</fieldset>
</form>
I have a form - search, this is layout and my task consistent in creation link to the controller with params like Products/index?search_name=something. And I dont know how I can transfer value textbox in my link.
Add onsubmit event handler to form, it should:
create Url with query string ?search_name= value from input
set window.location.href to created url
return false
EDIT: Of course, you can implement that in different way, the form is not needed in that case.
You have to give inputs the name they should have on posting and set the right action on the form. The name on the input determines what the key will be in the URL (since you use the GET method). Setting the action on the form will indicate where to send it to.
<form method="post" class="search-form" action="Products/index" method="GET">
<fieldset>
<input name="search_name" class="search home_input_search" placeholder="Поиск" type="search" />
<input type="submit" class="subm but_search" value="" />
</fieldset>
</form>
First of all there it'll be better to call controller paramter "searchName" instead of "search_name". That corresponds with code conventions.
Next, when you call Proudcts/index?search_name=somethink in browser you are initiating GET request. GET requests have no body and communicate with query parameters.
When you create new form and submit 'em to the server you are initiating POST request (by default). Post request has the body-section which contains request parameters.
Then we should start from View. If you want to use query-string you should explicitly create GET-form:
#using (Html.BeginForm("ControllerMethodName", "ControllerName", FormMethod.Get))
{
}
Next you should add name attribute to your input with the same name as in the controller method parameter:
<input class="search home_input_search" name="searchName" placeholder="Поиск" type="search" />
Or you can use HtmlHelper method to generate html:
#Html.TextBox("searchName", string.Empty, new Dictionary<string, object> { { "class", "search home_input_search" }, { "placeholder", "Поиск" } })
Finally you can have as many parameters as you need:
#using (Html.BeginForm("ControllerMethodName", "ControllerName", FormMethod.Get))
{
#Html.Label("Поиск")
#Html.TextBox("searchName", string.Empty, new Dictionary<string, object> { { "class", "search home_input_search" }, { "placeholder", "Поиск" } })
#Html.Label("Включая вложенные")
#Html.CheckBox("includeNested", true)
}
Related
I'm new to C#/Razor and don't know how to pass form data using the post method. Here's what I've tried:
In login.cshtml:
string username = Request.Form["username"];
string password = Request.Form["password"];
And
string username = Request.Form.Get("username");
string password = Request.Form.Get("password");
In _AppStart.cshtml, I tried:
AppState["username"] = HttpContext.Current.Request.Form["username"];
AppState["password"] = HttpContext.Current.Request.Form["password"];
All return nothing.
Here's the form elements in login.cshtml:
<form action="index.cshtml" method="post" data-ajax="false">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
If you need to pass data between MVC controller and View then you have to let Asp know which action an controller to call.
To accomplish this you could use something like BeginForms in razor an specify the needed information.
This would look like this:
#Html.BeginForm("YourAction", "YourController", FormMethod.Post){
#Html.TextBoxFor(employee => employee.FirstName);
#Html.TextBoxFor(employee => employee.LastName);
#Html.TextBoxFor(employee => employee.Age);
<input type="submit" value="Edit" />
}
Following this snippet you can see that you need A Controller and you name an ActionResult according to the name given here furthermore you can specify if you want to have the action only when posting or only for get forms
An possibile exemple could be the edit like the following code
[HttpPost]
public ActionResult YourAction(Employee emp)
{
if (ModelState.IsValid)
{
// do smth.
}
return View("Name Of the view");
}
Note you need to define this in your Controller and that the Attribute HttpPost lets Asp know that this is a post only ActionResult. This means that only post requests can use this Method. Furthermore
if you wish to have both get and post requests available for this ActionResult then you can simply delete the Attribute then per default it will be available in get and set requests.
You could look at this forum
entry
in Input Type "submit add formaction="ActionMethodName"
#using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="postedFile"/>
<input type="submit" **formaction="UploadData"** value="UploadData"/>
}
I have a view with a list of items. Each item have a textbox and a button.
What is the best way to get the item id of the button clicked in the controller action?
I need the value from the associated textbox in the controller action, so I do not think I can use action links.
There are a number of ways to do this. Some use javascript, others don't. I personally prefer to NOT use javascript for basic functionality, unless your design is itself javascript based (such as using ajax)
For instance, you can have each item be wrapped in it's own form, with a different submit value. Just be careful not to nest forms, as that's not valid HTML.
For instance:
#using(Html.BeginForm("MyAction", "MyController", new { id=1 })) {
<input type="submit"/>
#Html.TextBox("TheValue", "One")
}
#using(Html.BeginForm("MyAction", "MyController", new { id=2 })) {
<input type="submit"/>
#Html.TextBox("TheValue", "Two")
}
public ActionResult MyAction(int? id, string TheValue) {
// if they click the first one, id is 1, TheValue = "One"
// if they click the second one, id is 2, TheValue = "Two"
}
this answer is using jquery - If you do not know how to add jQuery to your view or just simply do not want to use it let me know and I can re-work the answer
I would do something like this
<li>
<input type="text" id="1" name="1" class="whatever" />
<input type="button" value="CliCk mE" class="myButton" />
</li>
<li>
<input type="text" id="2" name="2" class="whatever" />
<input type="button" value="CliCk mE" class="myButton" />
</li>
<input type="hidden" id="myHiddenText" name="myHiddenText" />
then add this jQuery:
<script>
$(function(){
$('.myButton').click(function(){
// this is how to get the closest textbox
// you didn't show your html , maybe .prev() or .next()
var textValue = $(this).closest("input[type='text']").val();
// this sets your hidden field with the value from desired textbox
$('#myHiddenText').val(textValue);
});
});
</script>
now when you submit this form to server you can just use myHiddenText on the server
public ActionResult Index(string myHiddenText = "")
{
// hidden fields in the HTML form automatically get passed to server on submit
return View();
}
The best option would be to use jquery but if you only want to use c# I would suggest the following:
I imagine you are using some sort of repeating statement (for or foreach) to generate your textboxes, so what I would do is create a form inside that foreach this new form would contain your textbox, and foreach item you would pass the textbox id to the form submit.
something like this pseudo code:
foreach(item in array){
<form action="address/"#item.Id>
<input type="text" value=""/>
<input type="submit" value="submit textbox"/>
</>
}
What I am trying to do is to open up a jquery dialog.
What is happening is that I see the following html text vs the rendering of the form when it tries to open up the PartialView:
<form action="/Plt/FileUpload" method="post"><input data-val="true" data-val-number="The field PlNum must be a number." data-val-required="The PlNum field is required." id="PlNum" name="PlNum" type="hidden" value="36028" /> <div id="errMsg" >
</div>
<p>File upload for Pl# 36028</p>
<input type="file" name="file" />
<input type="submit" value="OK" />
</form>
Here is the controller action:
public ActionResult FileUpload(int id)
{
var model = new FileUpload { PlNum = id };
return PartialView(model);
}
This is what the view looks like for the PartialView:
#model Ph.Domain.Lb.Models.FileUpload
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("FileUpload", "Plts", FormMethod.Post, null))
{
#Html.HiddenFor(a => a.PlNum)
<div id="errMsg" >
#if (TempData["ErrMessage"] != null)
{
#TempData["ErrMessage"]
}
</div>
<p>File upload for Pl# #Model.PlNum</p>
<input type="file" name="file" />
<input type="submit" value="OK" />
}
This is what my ajax call looks like:
var url = '#Url.Action("FileUpload", "Plt")' + '?id=' + encodeURIComponent(rowid);
$.ajax({
url: url,
type: 'GET',
success: function(result) {
if (result.success) {
$('#dialog').dialog('close');
} else {
// refresh the dialog
$('#dialog').html(result);
}
}
To recap, the ajax call does reach the ActionResult but not sure when it tries to show the partial view it shows HTML vs the rendered html.
The issue here is that you are trying to load razor view which has not been rendered into the dialog's innerHTML. Instead what you should be doing is setting href property of the dialog to the URL.Action link, when creating the dialog. See the link below for an example.
http://www.matthidinger.com/archive/2011/02/22/Progressive-enhancement-tutorial-with-ASP-NET-MVC-3-and-jQuery.aspx
The other option, which is not very maintainable IMO, but which will work with way you are currently doing, is to return the raw HTML from the action method.
I think the first solution is better because the controller is not polluted with HTML string concatenation.
jQuery won't let you use a script inside .html(). You can do this by two ways:
Native DOM HTML injection instead:
$('#dialog')[0].innerHTML = result;
.
Or, setting it as a data attribute and loading it manually:
In view:
<form action="/Plt/FileUpload" ...
data-script="#Url.Content("~/Scripts/jquery.validate.min.js")"
... />
In JS:
$('#dialog').html(result);
var dialogScript = $('#dialog').children().first().data("script");
if(!!dialogScript) { $.getScript(dialogScript); };
Reference: http://api.jquery.com/jQuery.getScript/
.
Another way is use the load method, as in:
$("#dialog").load(url, null, function() {
// on a side note, put $("#dialog") in a variable and reuse it
$("#dialog").dialog();
});
Reference: http://api.jquery.com/load/
.
In the very case of jQuery validation, I'd consider adding it to the parent page itself. You'd expect it to be used in fair number of situations.
Say I have the following form that's in classic asp:
<form name="impdata" id="impdata" method="POST" action="http://www.bob.com/dologin.asp">
<input type="hidden" value="" id="txtName" name="txtName" />
</form>
I need to simulate the action of submitting the form in asp.net mvc3, but I need to modify the hidden value before submitting. Is it possible to do this from the action or in another way?
What I have so far...
View:
#using (Html.BeginForm("Impersonate", "Index", FormMethod.Post, new { id = "impersonateForm" }))
{
<input id="Impersonate" class="button" type="submit" value="Impersonate" action />
<input type="hidden" value="" id="txtName" name="txtName" />
}
Controller:
[HttpPost]
public ActionResult Impersonate(string txtName)
{
txtName = txtName + "this string needs to be modified and then submitted as a hidden field";
//Redirect won't work needs the hidden field
//return Redirect("http://www.bob.com/dologin.asp");
}
Solution:
Seems that it isn't easy to do this from the controller so I ended up using jQuery. The action returns a JsonResult.
Something like:
<button id="Impersonate" class="button" onclick="Impersonate()">Impersonate!</button>
<form name="impdata" id="impersonateForm" action="http://www.bob.com/dologin.asp">
<input type="hidden" value="" id="txtName" name="txtName" />
</form>
function Impersonate() {
$.ajax({
type: 'POST',
asynch: false,
url: '#Url.Action("Impersonate", "Index")',
data:
{
name: $('#txtName').val()
},
success: function (data) {
$('#txtName').val(data.Name);
$('#impersonateForm').submit();
}
});
Seems to work well...
It is rather hard to redirect to a POST from a POST (relies on HTTP status codes without universal support), and it is impossible from a GET.
The simplest solution is probably a little JavaScript on the result that posts the (new) form.
Thus you action method returns a view with the necessary data in it (passed via the model from the controller) which will include the JavaScript.
You can try something like this(using jquery):
<input id="Impersonate" class="button" type="submit" value="Impersonate" onclick="$('#txtName').val('new value')" />
I'm using MVC with Razor and C#. I would like to update an element... a counter with ajax. Here is my code:
#model Domain.CounterObject
#using (Ajax.BeginForm("Count", "CounterObject", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "my-control" }))
{
<div id="my-control" class="bid-object">
<div>
<span class="title">#Html.Encode(Model.Title)</span>
</div>
<div>
<span class="display">#Html.Encode(Model.GetFinalDate())</span>
</div>
<div>
<span class="display">#Html.Encode(Model.GetValue())</span>
</div>
<div>
<input type="submit" value="Count" />
</div>
</div>
}
In my controller I have this code:
[HttpPost]
public PartialViewResult Count(CounterObject counter)
{
// Special work here
return PartialView(counter);
}
The problem is that my CounterObject counter I receive in my Count method is always null. How can I pass a value from my page to the controller?
I receive in my Count method is always null
First of all you are not submitting anything from the form then how does the binding happens?
If the user is not allowed to edit the values but still you want to submit them through the form then you have to use hidden fields along with them.
For ex.
<div>
<span class="title">#Html.Encode(Model.Title)</span>
#Html.HiddenFor(m => m.Title)
</div>
Note that the hidden fields should have the same names as the properties to make the binding happen successfully.
It is better to have properties in the Model that store the GetFinalDate() and GetValue() results so you can easily bind the things like in Title.
You'll have to define a input field with a name and id that the ModelBinder can then Bind to your CounterObject.
You could use #Html.EditorForModel once and then inspect the generated Html to see what kind of name/id pairs it is generating. With those you can go on and handcraft your Html if you wanted to.
use
<span class="title">#Html.Encode(Model.Title)</span>
<div class="editor-field">#Html.EditorFor(Model => Model.Title)<div>
//For other fields
In this way you can bind to your object.