How do I render a partial form element using AJAX - asp.net

I have a form that assembles sections of a larger form. For example:
Html.RenderPartial("Partials/MealPreference", Model);
I would like to dynamically add sections to the form. Given the nature of my partial views, I must pass the model along as well. In that, I am failing miserably.
The markup on my containing page:
<div id="additionalPreference"></div>
<input type="button" value="Add Additional Preference" id="addPreference" />
<script>
$(document).ready(function () {
$('#addPreference').click(function () {
$.ajax({
type: "POST",
url: '#Html("AddPreference", "Main")',
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
}
});
});
});
</script>
My controller action:
[HttpPost]
public ActionResult AddPreference(FormViewModel model)
{
if (ModelState.IsValid)
{
return PartialView("Partials/AdditionalPreference", model);
}
else
{
return PartialView("Partials/LoadFailed");
}
}
The model is never valid. How do I pass the model form the containing page to the controller action? This would seem to be something simple to do (it certianly would be in Web Forms) but I have been choking on this for 3 hours.

For an ajax call you have to build the model:
$.ajax({
type: "POST",
url: '#Url.Action("AddPreference", "Main")',
data: {
Field1: 'field1',
Field2: 'field2'
},
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
});
Make sure that the names in the data section of the ajax call match exactly the names in your model and it should show up in your controller populated.
update:
Since writing this answer I have learned more about sending information back to the controller via ajax. As commented by Rick Dailey you can send the model submitted to the form back to the controller via:
#Html.Raw(Json.Encode(Model))
I have found out about serialize and we use:
$('form').serialize()
To send the fields on the form back to the controller. A quick, easy way to send all information back similar to a post back without having to manually build the model.

You need to add the properties of the model for the controller you are calling in the ajax request. In this case your AddPreferencecontroller has a parameter of type FormViewModel. I assume the information for the FormViewModel is stored on the page. You need to pass those in the data property for the ajax request.
If you post your FormViewModel properties I could help futher. Bascially you need to the following:
$('#addPreference').click(function () {
$.ajax({
type: "POST",
url: '#Html("AddPreference", "Main")',
data: {id: "123asd", Prop1: myProp1},
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
}
});
Post more information of your model and the view you are making the ajax request and I can assist further.

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

How do I write my ajax code to move from razor view to another?

In my Save button ajax code I'm looking to redirect back to another razor page if a successful save occured. How would I do that?
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/StorageRequests/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
alert('Thank you for your delivery time!');
}
},
error: function () {
alert('Failed');
}
})
You can use window.location.href
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
window.location.href='/{your razor page url relative to website root}';
}

Viewdata not showing in partial view

Hi guys i have controller which returns a partial view, the controller is called by ajax script. The partical view has no problem showing viewdata first time, But when ajax script is invoked second time the partical view does not update it self with new viewdata.
code for controller
[HttpGet]
public ActionResult getPart(int id)
{
ViewData["partical"] = id;
return PartialView("test");
}
code for partial view
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PovertyBayHotel.Models.testmodel>" %>
<p>just a test</p>
<%: ViewData["partical"]%>
and the ajax which call the controller
<script type="text/javascript">
$(document).ready(function () {
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
});
});
</script>
Might be a caching issue. Try HTTP POST instead of GET or set the ifModified and cache options to false as below:
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
ifModified: false,
cache: false,
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
Also, try to debug your code and see really what is going on.
Edit:
The problem has been solved by changing $('#ExtraBox').replaceWith(data); with $('#ExtraBox').html(data);.

Ajax success when a view is returned

I'm struggling to return a view or partial view with Ajax. Whenever I change the return type to something that isn't JSon the ajax command never succeeds. I need to return a partial view because I want to return a lot of data back.
This is my current code:
(Controller)
[HttpPost]
public ActionResult AjaxTestController(string Input)
{
string Results = Input + " -- TestTestTest";
return PartialView("Test", Results);
//return new JsonResult() { };
}
(View)
function AjaxTest() {
alert("test");
$.ajax({
type: "POST",
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function () {
alert("Success!");
}
});
Thanks!
You can use the $.post command for that:
function AjaxTest() {
alert("test");
$.post({
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function (response) {
alert(response);
}
});
try the following:
$(function () {
$('#submit').live('click', function () {
AjaxTest();
});
});
function AjaxTest() {
$.ajax({
type: "POST",
url: '#Url.Action("AjaxTestController", "Home")',
data: { Input: "Test - " + new Date() },
success: function (data) {
$('#partialResult').html(data);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
};
inside your view and ensure that you have your target div set up for the partial to be populated into:
<div id="partialResult"></div>
also, for the example above, I added a button to the view to initiate the ajax (purely for testing):
<input type="button" value="Submit" id="submit" />
your 'partialview' should look something like this:
#model string
<h2>
Partial Test</h2>
<p>
#Model
</p>
no other changes are required to the existing action for this to now function as required.
[UPDATE] - I changed the AjaxTest() method to include the error event (the result of which is captured in an alert). hopefully, this may help further.
partial View is different than view you have to specify the whole path to the partial view or have it in share folder. otherwise is going to return not found and never success. any way this always work for me, try
partialView("~/Views/ControllerView/Test.cshtml")

Fire a controller action from a jQuery Autocomplete selection

I have a jQuery autoselect box displaying the correct data. Now I would like to fire an ASP.NET MVC 3 controller when an item is selected. The controller should then redirect to a View. Here's my jQuery autocomplete code (I'm sure something is missing in the 2nd Ajax call, but I haven't found it yet):
<script type="text/javascript">
$(function () {
$("#Client").autocomplete({
source: function (request, response) {
$.ajax({
url: 'Entity/GetClientAutoComplete', type: 'POST', dataType: 'json',
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item, value: item };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$.ajax({
url: 'Entity/GetApplicationsByName/' + ui.item.value, type: 'POST'
})
}
});
});
</script>
And here's the controller I'm trying to call:
public ActionResult GetApplicationsByName(string id)
{
ViewBag.Client = id;
var apps = _service.GetDashboardByName(id);
return View("Dashboard", apps.ToList());
}
When I watch the Ajax call fire in Firebug, I see the correct URL configuration, but nothing else happens. It's acting as though it wants to load something rather than send something. I'm confused. Thank you for any guidance.
Well you sent an id by POST to the GetApplicationsByName controller and the controller is sending back the view.
If you want redirection, you can use the following:
select: function (event, ui) {
window.location.href = 'Entity/GetApplicationsByName/' + ui.item.value;
}

Resources