I am facing a weird problem. I have a cshtml form:
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "1", (Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnYes", style = "margin-top:0px; margin-right:10px;" })Yes</label>
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "2", !(Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnNo", style = "margin-top:0px;margin-right:10px;" })No</label>
On form submit, I am getting radio group value like this:
int radioValue = int.Parse(fc.GetValue(controlID).AttemptedValue);
It works fine when i call it from #Html.BeginForm(), but when i try to send form collection via ajax like this:
input = $(':input')
$.ajax({
type: "POST",
url: '#Url.Action("SavePrerequisiteQuestion", "Dashboard", new { id = #Model.ID })',
data: input,
dataType: "html",
success: function (msg) {
alert("fine");
}, error: function (req, status, error) {
// with error
alert(error);
}
});
It send both values like this "1,2" rather than sending just selected/submitted value.
In your ajax request, you're sending all :input elements as your data:
...
data: input
...
What you probably want is to just serialize your form data, and send it with the request:
...
data: input.closest('form').serialize()
...
This is assuming you have your radio buttons in a <form> tag.
It may not be so easy to work around this. For instance, to get a selected radio button, you can do this: jQuery get value of selected radio button
So you can't just take all inputs and get the values from them... instead, you have to have more of a selective approach, and handle different elements appropriately. Checkboxes and selects will also have a similar problem.
You can put the #Html.Beginform back in and hijack the form submit in your jQuery
$('#formID').on('submit', function(e){
e.preventDefault(); // Just to stop the automatic Non Ajax submission of the form
$.post($(this).attr('action'), $(this).serialize(), function (data) {
//do stuff on success callback
alert("fine");
});
});
You can inherit the action path from the Html.BeginForm itself in the path below by doing
$(this).attr('action')
Note: If you want to manually put the path in there you still can instead of getting it
from the form
Then use $(this).serialize() to just serialize the whole form like the person above me
suggested
Related
I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty
I am making my MVC application. How do I create a button in my view that a click on it will run a function from controller. I would also like to pass data from the view that the button is in. But I do not want to open a different view. I just want to run a function - Button "save to file" would save the table from the view into a file - would open a Directory browser and save a file on a disk.
This will be done with the help of ajax request from your view. You need to add a simple button on your view and call a jquery function on its onclick event like this:
<input type="button" value="save to file" onclick="saveToFile()" />
Then you can create saveToFile function to send ajax request like this: here you can create your data as per your need of fields you want to post to controller. I just adding firstField and secondField for demo:
<script type="text/javascript">
var data = { "firstField" : "value1", "secondField": "value2" };
function saveToFile() {
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
},
error: function (xhr) {
console.log(xhr);
}
});
});
</script>
Your action method will be like this:
[HttpPost]
public ActionResult UseShippingAddress(string firstField, string secondField)
{
//write your logic here to save the file on a disc
return Json("1");
}
Apparently, the correct solution was to use
#Html.ActionLink("weekly - PDF", "GenerateTable", "Account", new { group_id = Model.group_id, class_id = Model.class_id, type = 1 }, null)
And in GenerateTable method just return a proper file.
im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.
From razor view I'm sending js object using jquery to the mvc controller. Reason why I do it using jquery post method and not razors form is that I need to manage dynamic input of certain fields. On the view certain fields (inputtextbox) are dynamically added to the view (from 0 - 10) and I manage that solution using js on the page.
var myJsObj = ...
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/MyController/SomeAction',
data: JSON.stringify({ model: myJsObj}),
success: function () {
}
});
On the server side, mvc receives that model and in case of some error I want to return this object back to the view.
[HttpPost]
public ActionResult SomeAction(MyModel model)
{
if(!ModelState.IsValid)
{
ModelState.AddModelError("", "Error occured!");
return View(model);
}
return RedirectToAction("Index");
}
I have inside razor view
Html.ValidationSummary
but since I'm using jquery post I dont know how to receive back to the view and display error like I would use regular razor form. Or if you know better approach to manage dynamically added input boxes on the razor view please post. Any help please.
I think you've got a couple of options here:
If you prefer to continue to use an Ajax POST as you've shown above, then you need to take the response from the POST and inject it back into your current HTML document. For example,
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/MyController/SomeAction',
data: JSON.stringify({ model: myJsObj}),
success: function (data) {
// This is the case where the MVC action found model validation
// errors, and so it is responding with an HTML document that
// shows the errors.
var returnedBodyHtml = $(data).find('body').html();
$('body').html(returnedBodyHtml);
}
});
(That's untested code up there, so you may have to debug a little bit.) But this code doesn't handle the case where the server responded with a redirect (in the case of successful validation). So, check out this post for some options there.
Your other option is to use the standard Form submit. I know you said you had some dynamically generated input controls on your page, but that doesn't mean that you can't do a Form submit. You just need to make sure that these dynamically generated elements have the correct "name" attribute on them, so that their values get mapped appropriately to the Model on the server side action that is accepting the POST. For example, if your Javascript is dynamically generating an HTML element like this, and inserting it into the form:
<input type="text" name="myDynamicallyGeneratedInput[0]" />
<input type="text" name="myDynamicallyGeneratedInput[1]" />
<input type="text" name="myDynamicallyGeneratedInput[2]" />
<input type="text" name="myDynamicallyGeneratedInput[3]" />
then your Form submit will still work, as long as on the server side, your MyModel class has that corresponding property:
class MyModel
{
public List<string> MyDynamicallyGeneratedInput {get; set;}
}
This is what I have done to display errors for dynamic inputs. First off, take a look at this post to give you a better understanding. I have modified my code to better suit my needs, but you can check if it works for your application.
use-asp-net-mvc-validation-with-jquery-ajax.
I would then consume the return result in the ajax post error callback. It returns a code 400 'Bad Request' on validation errors. The validator variable is the form validator object.
error: function (xhr, textStatus, errorThrown) {
var statusCode = parseInt(xhr.status);
if (statusCode == 400) {
var data = $.parseJSON(xhr.responseText);
var message = "";
$.each(data, function (i, item) {
var propertyName = "" + item.key + "";
if ($("input[name='" + item.key + "']").length > 0) {
var errorObj = {};
errorObj[item.key] = item.error;
validator.showErrors(errorObj);
}
else {
message += "<div>" + item.key + ": " + item.error + "</div>";
}
});
if (message != "") {
//display message
}
}
}
I hope this helps. Good luck.
I have this Kendo UI dropdownlist with a select event that is handled by a JavaScript function.
I need to call an action result from a controller that runs a LINQ query to populate a Kendo UI grid on my page. My problem is the only way I can find to handle this even is with JavaScript and I have been unable to figure out how to call my action result from my controller from the JavaScript event function.
This is what the DropDownList looks like...
#(Html.Kendo().DropDownList()
.Name("Options")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Policies Not Archived",
Value = "1"
},
new SelectListItem() {
Text = "View All Policies",
Value = "2"
},
new SelectListItem() {
Text = "Filter Policies",
Value = "3"
}
})
.Events(e =>
{
e.Select("select");
})
)
and my JavaScript event handler that needs to call the action result
function select(e) {
}
and depending on the selection an ActionResult like this,
public ActionResult ViewAllPolicies()
{
//mycode
}
see this post
var url = '#Url.Action("ViewAllPolicies","YourController")';
$.ajax({ url: url, success: DataRetrieved, type: 'POST', dataType: 'json' });
in controller
public ActionResult ViewAllPolicies()
{
//Should return json format
}
url – this is the URL where request is sent. In my case there is
controller called contacts and it has action calles
ListPartiesByNameStart(). This action method takes parameter
nameStart (first letter of person or company). success – this is the
JavaScript function that handles retrieved data. You can write there
also anonymous function but I suggest you to use functions with names
because otherwise your code may get messy when functions grow. type –
this is the type of request. It is either GET or POST. I suggest you
to use POST because GET requests in JSON format are forbidden by
ASP.NET MVC by default (I will show you later how to turn on GET
requests to JSON returning actions). dataType – this is the data
format that is expected to be returned by server. If you don’t assign
it to value then returned result is handled as string. If you set it
to json then jQuery constructs you JavaScript object tree that
corresponds to JSON retrieved from server.
Instead of returning json, you can also return a PartialView and in the .done function grab an element and replace it with the results from the partial view. PartialView actions basically return a fragment of HTML, and so you can just stuff that anywhere you want on the page:
$.ajax({
url: urlToPartialViewAction,
type: 'POST',
dataType: 'JSON',
data: '123'
})
.done(function (result) {
$('#someDivPlaceholder').replaceWith(result);
});
You could have something like a link or grey div and wire up to it's click event and then call this, the link might say "View Receipt" and when you click it you call an action that returns a partial view with the receipt, and so when they click it the div/link is replaced with the result. Kind of like the "View More Comments" links you see on social sites.
Note that you can't have a partial view by itself, it must be called through an action
public PartialViewResult _GetReceipt(string id)
{
ReceiptViewModel vm = //query for receipt data
return PartialView(vm);//render partial view and return html fragment
}
Once the select function executes, you need to make an AJAX call back to your Controller. You can use jQuery.ajax() (a wrapper for the most common AJAX operations) in the select function,
function select(e) {
var url = '#Url.Action("ViewAllPolicies", "PolicyController")';
var selectedPolicy = $('#Options').val(); // The option selected
$.ajax({
url: url,
type: 'POST',
dataType: 'JSON',
data: selectedPolicy
})
.done(function (data) {
// Display the data back from you Controller
});
}
You can look at the Kendo site for more info on how the DropDownList works.