Viewdata not showing in partial view - asp.net

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

Related

Load Partial View based on Autocomplete Selection

I'm just learning ASP.NET, MVC, and JScript for the first time. I'm attempting to use the selection from an autocomplete to do an ajax call get data and load a partial view with that data. The controller gets the request with the selected Id, but the partial view never loads. What am I doing wrong?
(the view and partial view have different models - I didn't think that would be an issue)
CONTROLLER
public ActionResult GetEmployee(int id)
{
HumanResourcesManager man = new HumanResourcesManager();
var emp = man.GetEmployee(id);
return PartialView("_EmployeeDetails", emp);
}
VIEW
#model HumanResources.Web.Models.EmployeeModel
<p>
Selected Employee: #Html.TextBox("EmployeeSearch")
</p>
<script type="text/javascript">
$("#EmployeeSearch").autocomplete({
source: function (request, response) {
                $.ajax({
url: "#(Url.Action("FindEmployee", "Employee"))",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayName, value: item.DisplayName, id: item.Id };
                        }))
                    }
                })
},
select: function (event, ui) {
if (ui.item) {
GetEmployeeDetails(ui.item.id);
}
}
});
function GetEmployeeDetails(id) {
$.ajax({
url: '/Employee/GetEmployee',
type: 'POST',
async: false,
data: { id: id },
success: function (result) {
$("#partialView").html(result);
}
});
}
</script>
<div id="#partialView">
#*Partial View Test*#
</div>
PARTIAL VIEW
#model HumanResources.Objects.Employee.EmployeeInformation
#{
Layout = null;
}
<h1>THIS IS A TEST</h1>
Remove the # from your partial view div id. You only add it when you're using jQuery's id selector.
<div id="partialView">
#*Partial View Test*#
</div>

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

How do I render a partial form element using AJAX

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.

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