Passing a parameter to Action method - c#

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;
});

Related

Sending simple type from HTML form to ASP API

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

How do I call my method in html?

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");
}
});
});

Ajax Form Begin is not going to http GET method

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");
}

How to add additional data in my JQUERY submit?

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() + '&parameter=param1' ,
success: function () {
alert("Successful");
}
error: function(){
alert('error');
}
});
});
Hope it helps.
Edit
Try like this in your jQuery function:
$('form').append('&param=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" />
}

ASP.NET MVC JSON Post a HTML Form to a View?

I have the following code:
jQuery:
$.ajax({
url: '/personcontroller/getperson',
cache: false,
type: "POST",
data: $('#person').serialize(),
success: function(data) {
alert('yay');
}
});
});
Controller:
public ActionResult getPerson(Person person)
{
return new Json(person);
}
Html Form/Spark:
<form id="person">
<input id="person.Id" type="hidden" value="${ViewData.Model.Person.Id}" />
<input id="person.Name" value="${ViewData.Model.Person.Name}"></input>
<input id="person.Age" value="${ViewData.Model.Person.Age}"></input>
<input value="${ViewData.Model.Person.Gender}"></input>
</form>
When I POST the ajax call with the form, and put a break point in my action. The person object is not being populated with the input values, I feel like I am overlooking something really simple... Can you please point it out to me :|
Inputs need a name attribute to post correctly. You should add a name attribute that matches the Id.
<form id="person">
<input id="person.Id" name="person.Id" type="hidden" value="${ViewData.Model.Person.Id}" />
<input id="person.Name" name="person.Name" value="${ViewData.Model.Person.Name}"></input>
<input id="person.Age" name="person.Age" value="${ViewData.Model.Person.Age}"></input>
</form>
You should use:
public ActionResult getPerson([Bind(Prefix="person")]Person person)
EDIT
And as Michael Gattuso noticed, you should populate name property.

Categories