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");
}
Related
Hello
I am using ajax.beginform and i want to return partial view with the
errors inside. whan I change the status code to something bad to fire
the OnFailure method it is not returning the partial view. the view that called:
<fieldset>
#using (Ajax.BeginForm("SaveSocioDetails", "Student", new AjaxOptions { HttpMethod = "POST", OnSuccess = "firstsuccess",OnFailure = "sociodetailsfail", UpdateTargetId="partialsocio" ,LoadingElementId = "div_loading" }, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="partialsocio">
#Html.Action("PartialSocioDetails", "Student", new { SpId = ViewBag.SpId })
</div>
<div id="div_loading" style="display:none;">
<img src="#Url.Content("~/Content/Pic/Spinner.gif")" alt="" />
</div>
<button class="btn btn-primary" type="submit" value="Submit">שלח</button>
}
<input type="button" name="next" class="next action-button" value="Next" />
my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSocioDetails(SpSocio socio) // ajax for 1 step in socio
{
socio.StudentId = sStudentId; // bind student id to socio model
bool sociook = SocioDetValid(socio);
// add validation
if (ModelState.IsValid && sociook)
{
SaveSocioModel(socio);
Response.StatusCode = 200;
}
else
Response.StatusCode = 300; // return error to client the model is not valid
return PartialView("~/Views/Student/Socio/SocioDetails.cshtml", socio); // return the partial view of the forn with validation messages
}
js:
<script>
$(document).ready(function ()
{
});
function firstsuccess(data) {
console.log(data);
$('#partialsocio').html(data);
console.log('this is ajaxSuccess');
}
function sociodetailsfail(bdata) {
console.log('this is ajaxfail');
console.log(data);
$('#partialsocio').html(data);
}
</script>
please help me out with this
If your request fails then you will get the callback from server including problem definition inside sociodetailsfail witin java-script, where you can put logic to display error messages that you receive from server bdata object to user
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'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;
});
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.