In my razor view, I'm using a Html.BeginForm. In it I have two elements where when I set clic, should submit the form but I need to add an additional string parameter.
#using (Html.BeginForm("Index", "Quiz", FormMethod.Post, new { id = "form" }))
{
...
}
[HttpPost]
public ActionResult Index(string parameter, QuizCompletedViewModel q) //FormCollection f)
{
...
if (button.Equals("d"))
{
...
return RedirectToAction("ShowResults", new { testId = Quiz.QuizId, answeredTest = answeredId });
}
else
{
...
return RedirectToAction("Index", "Dashboard");
}
}
So, in my jquery function I utilize $("#element").submit() and the parameter parameter always is null (and that's normal). How can I add additional data for parameter using JQUERY?
NOTE: I'm not using AJAX.
On your form sumbit try like this:
$("form").submit(function(){
$.ajax({
type: 'POST',
url: "/Quiz/Index",
dataType: "json",
data: $("form").serialize() + '¶meter=param1' ,
success: function () {
alert("Successful");
}
error: function(){
alert('error');
}
});
});
Hope it helps.
Edit
Try like this in your jQuery function:
$('form').append('¶m=a');
You could add a hidden input with the name and value you require in your form. This value will be submitted along with all the other form items.
<input type="hidden" name="someName" value="someValue" />
Edit for comment:
If you give each of your submit buttons the value as an attribute you could grab it in the click handler and then append a hidden field with the value inside the form. Something like:
$(function(){
$('#form input[type=submit]').click(function(e) {
var val = this.getAttribute("data-param");
$(this).closest('form').append('<input type="hidden" name="param" value="' + val + '" />");
});
});
Untested, just a hunch. Hope that the form submit event does not get fired before the button click event. Also you will need to handle the enter event and key press etc.
Why don't you want to use ajax?
Based on your comments, the easiest thing for you to do is make your buttons of type submit and give them a name. If they have a name, the value of the button that is clicked will be sent automatically with the form post, see: sending form's submit button's value?
Example:
When the a button is clicked, parameter will be posted with value a. Likewise for b and c. If the none button is clicked, no value will be sent and parameter will be null (shown for demonstration purposes, you may not need this).
#using (Html.BeginForm("Index", "Quiz", FormMethod.Post, new { id = "form" }))
{
...
<input type="submit" value="a" name="parameter" />
<input type="submit" value="b" name="parameter" />
<input type="submit" value="c" name="parameter" />
<input type="submit" value="none" />
}
Related
I am having troubles with sending a simple double number from form to ASP API.
When I submit the form, I firstly need to remove Submit button to avoid sending a redundant 'submit=Submit' value to API controller.
As I have read in this article, I set the name of my input field to be empty. So if I check the http request in Developer mode, the body of sent data looks like so '=value'. My method parameter is decorated with [FromBody] attribute.
Even with all this, the controller method does not get the value. It is allways zero.
What to do?
My form looks like so:
<form action="#Url.Action("Temperature","Api")" method="post" >
<input type="number" name=" " step="0.25"/>
<input type="submit" name="submit" />
</form>
</div>
<script>
$("form").submit(function () {
$(this).children('[name="submit"]').remove();
});
</script>
The controller:
// POST: api/Temperature
public void Post([FromBody]double value) //FormDataCollection data
{
Temperature newEntry = new Temperature() { Timestamp = DateTime.Now, Value = value};
try
{
db.Temperatures.Add(newEntry);
db.SaveChanges();
}
catch(Exception e)
{
Debug.WriteLine(e.Message);
}
}
Try Ajax...
Change your Html little bit like this:
<div>
<input type="number" id="number" name=" " step="0.25"/>
<input type="button" id="submit" name="submit" />
</div>
Then:
$(document).on('click', '#submit', function () {
$.ajax({
type: 'POST',
url: '/ControllerName/Post',
data: {
value: JSON.stringify($('#number').val())
},
success: function (data) {
alert(data);
},
error: function (data) {
alert("An Issue has occured");
}
});
})
Also your controller input parameters would be like:
public void Post([FromBody]string value) //convert string to double later within method
I want to call my method in my mvc view. I have a method called SavePersoon wich has to save the changed data into my database. This is my code from my services:
public bool SavePersoon(PersoonModel persoon)
{
bool result = true;
db.Persoon.AddOrUpdate(persoon.GetPoco());
db.SaveChanges();
return result;
}
This is the button who has to be pressed and then this code above has to deal the work itself.
The view:
<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>
Do I have to use something similair like <asp:LinkButton...?
You can make use of Ajax , Something like this
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
If you use Razor view engaine, you can make your method return an action result and call it from the view using Html.Actionlink.
You can do 2 things:
Use the HTML Helpers that ASP.Net MVC provides to create a form which posts to the required method, something like 'Save' of the controller 'Person':
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { #class = "form-horizontal" })) {
<div>
<!-- Your HTML, this could for example be a text field for the person its name -->
#Html.TextBoxFor(Model => Model.Name, new { #class = "form-control" })
<input type="submit" class="btn btn-primary" value="Save" />
</div>
}
This will create a form tag for you, something like <form action="person/save" method="post"> ... your HTML & the submit button ... </form>
An alternative is to use Ajax to prevent the page from refreshing as stated in the above post.
$("#btnSaveChanges").on("click",function(){
$.ajax({
url: '#Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
data:$("#Name").val(), // Posts the value of a text field with ID "Name"
cache:false,
type:"POST",
success: funcion(returnValue) {
// Do something with the result.
}
error:function(){
alert("Error");
}
});
});
I am trying to send the text box values in ajax form begin and show the corresponding partial view But the problem is it always going to the post method but i mension the httpmethod also in ajax form
My Code is
#using (Ajax.BeginForm("UserMenuPermission", new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "GridData" }))
{
<div>
#Html.Label("User Name")
<input type="text" placeholder="User Name" style="color: black;height:30px;" name="Username"/>
<input type="submit" value="Search" />
</div>
}
This code can pass the information to UserMenuPermissionController POST method but i need to pass in GET Method Please Help Me Friends
Thanks In Advance.
I Suggest that use jquery.ajax get method
//Change your search button like this
<input type="button" value="Search" onclick="ajaxCall()" />
//in javascript
function ajaxCall()
{
$.ajax({
url: "ActionURL",
type:"get", //send it through get method
data:{}
success: function(response) {
//response is your partialview html
},
error: function(xhr) {
//Do Something to handle error
}
});
}
in controller
public ActionResult GetHtml( )
{
return PartialView( "UserDetails");
}
I'm trying to use a form to allow the user to pick a date and pass it back to the controller by way of url parameters. My intention is to have the form submit a url that looks like Payroll/Index/id?employeeID="foo"?DayInWeekInput="bar". Instead this generates the url Payroll/Index/id? so I'm obviously doing something wrong. How can I do this with a form? If it's not possible, could you explain an alternative? Thanks.
using (Html.BeginForm("Index", "Payroll", new { id = #ViewBag.SupervisorID, employeeID=#ViewBag.EmployeeID }, FormMethod.Get))
{
#*#Html.AntiForgeryToken()*#
#Html.ValidationSummary(true)
<div class="editor-field">
<input type="date" id="DayInWeekInput" value="#string.Format("{0:yyyy-MM-dd}", Model.SpecifiedWeekStart)" />
<input type="submit" value="Go" />
</div>
}
you stopped naming, if you keep the names up it should work for you
using (Html.BeginForm("Index", "Payroll", new { id = #ViewBag.SupervisorID, EmployeeID = #ViewBag.EmployeeID, DaysInWeekInput = "bar" }, FormMethod.Get))
Since that didn't work for you I would try an ajax call next
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action( "Index", "Payroll" )',
data: {
id: #ViewBag.SupervisorID,
EmployeeID: #ViewBag.EmployeeID
},
success: function (_result) {
if (_result.Success) {
}
}
});
});
I would also recommend putting your id's in hidden fields. Viewbag can be unstable.
I have an action method like this
public JsonResult Create(Product p, string extra)
The view is bound to #model Product
On calling Create action via ajax call, I am getting Product P values from the form but extra is always null, although extra is in the same form
<input type="text" name="extra" />
I also tried Request.Form["extra"] it was null too. What I am missing? how to get value of input[name=extra] in action method?
You didn't mention how are you calling this action (other than saying AJAX which obviously is not enough), so assuming you have an HTML form representing a product and an input field containing some extra value:
#model Product
#using (Html.BeginForm())
{
#Html.EditorForModel()
<input type="text" name="extra" value="some extra value" />
<input type="submit" value="Create" />
}
you could unobtrusively AJAXify this form like this:
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
// TODO: handle the results of the AJAX call
}
});
return false;
});