Partial View not showing updated model values. Always shows existing values - asp.net-mvc

Actually i tried to update the partial view content whenever i do search. So i use ajax call to achieve this. So, the values from the controller to partial view model is correct(new data), but its not binding to the view (shows existing data).
Main View
<div class="tab-pane active" id="partialviewpage">
#{
Html.RenderPartial("_Details", Model);
}
</div>
Partial View (_Details)
foreach (var item in Model.AllAds)
{
//div contents
}
Ajax Call
var text = 'test';
$.ajax({
url: '#Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Category Controller
public ActionResult Subcategory(string item)
{
//Logic calling Api content goes here
var SearchresponseData = responseMessage.Content.ReadAsStringAsync().Result;
JavaScriptSerializer JssSearch = new JavaScriptSerializer();
List<Result> Jsonresult = (List<Result>)JssSearch.Deserialize(SearchresponseData, typeof(List<Result>));
var Model= new ModelName();
{
Model.AllAds = new List<Result>();
Model.AllAds = Jsonresult;
}
return PartialView("_Details", Model);
}
So, What's wrong with my code and how can i modify the code to get the new model values. Any help appreciated. Thanks in advance.

I observed that you have used wrong variable to replace the html in success,
I have replace PartialView to partialView
var text = 'test';
$.ajax({
url: '#Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});

Related

jquery ajax load partial view to div tag MVC

I've been searching around with no luck on how to make a jquery call to load a partial view in a div tag on my Index view. Some how I am not getting the partial view to update when I click on a link on my tree. The partial view loads when I first run it b/c I call <div id="divid">
#Html.Partial("_InnerView")</div>. After that nothing happens when I click on the link. Or maybe I am not getting the full picture here. Some mentioned to use $('#divid').load = data; or $('#divid').innerHTML= data; but nothing works for me. This is what I have.
Controller:
public ActionResult Test(string parentEls)
{
if (Request.IsAjaxRequest())
{
Employee employee = new Employee();
employee.Name = parentEls + "1";
return PartialView("_InnerView", employee);
}
return View("_InnerView");
}
Index view:
<div id="divid">
#Html.Partial("_InnerView")</div>
$('#tree a').click(function () {
var parentEls = $(this).parents('ul').map(function () {
return $(this).find('a').first().text();
}).get().join(", ");
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
});
_InnerView.cshtml:
#model TreeDemo.Models.Employee
EmpName:#Model.Name
UPDATE: I got this to work with this
$.ajax({ url: '/Home/Test/', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'html', data: { parentEls: parentEls } })
You have to use
$('#divid').html(data);
instead of
$('#divid').innerHTML = data;
Load Partial View in a div MVC 4
Recently I want load Partal View in Div , after doing lots of R&D and It's work for me
$.ajax({
type: 'POST',
url: '#Url.Content("~/ControllerName/ActionName")',
data: {
title: title
},
success: function(result) {
$('#divid').innerHTML = result;
}
});
And In Partal View Action Controller Code
public PartialViewResult ShowCategoryForm(string title)
{
Model model = new Model();
model.Title = title;
return PartialView("~/Views/ControllerName/PartalView.cshtml", model);
}
I think it can be useful if you check the request/response objects of your call, so you can see what is really happening after you make the call... As per your code, I can notice that you're posting using
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
but your action is marked for 'getting'... you'd need to have something like this
[HttpPost]
public ActionResult Test(string parentEls)
so MVC can understand that the action should be called when HttpPost verb is used

MVC: Result from JSON Automatically fill View

I am stuck in publishing the result from JSON so left the success portion blank.
View
#model MvcApplication2.Models.About
#{
ViewBag.Title = "About";
}
<p> #Html.DisplayFor(m=>m.test) </p>
<p> #Html.DisplayFor(m=>m.test1) </p>
Model
public class About
{
public string test { get; set; }
public string test1 { get; set; }
}
Controller
public class HomeController : Controller
{
public JsonResult About()
{
ViewBag.Message = "Your app description page.";
About ab = new About()
{
test = "a",
test1 = "b"
};
return Json(ab, JsonRequestBehavior.AllowGet);
}
}
JQuery in external file
$(document).ready(function () {
var itemName = "#btn-about";
$(itemName).click(function () {
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (data) {
var option = '';
},
error: function (xhr, ajaxOption, thorwnError) {
console.log("Error")
},
processData: false,
async: true
});
});
});
=> I am a bit confused now. Altough I get a result in JSON format using AJAX, I want to publish it in this View 'About'. The View already have #model defined, so as soon as I get the result, I want the view to load it automatically as I don't think its a good option to create html controls in Javascript.
=> Is it possible or do I have to fill control one by one.
=> I am new in to MVC, so could you let me know any good suggestion.
Controller:
public ActionResult About()
{
var model = repo.GetModel();
return PartialViewResult("about", model);
}
jQuery:
$.ajax("/Controller/About/", {
type: "GET",
success: function (view) {
$("#aboutDiv").html(view);
}
});
In Main View:
<div id="aboutDiv"><div>
You need to give your elements some id or class that will allow you to interact with them easily on the client. Then, when you get your response, take the values from the JSON data and update the elements (using the id/class to find it) with the new value. I'm assuming you don't have any special template defined for your strings, adjust the selectors in the code as necessary to account for it if you do.
View
<p class="testDisplay"> #Html.DisplayFor(m=>m.test) </p>
<p class="test1Display"> #Html.DisplayFor(m=>m.test1) </p>
Client code
$(document).ready(function () {
var itemName = "#btn-about";
$(itemName).click(function () {
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (data) {
$('.testDisplay').html(data.test);
$('.test1Display').html(data.test1);
},
error: function (xhr, ajaxOption, thorwnError) {
console.log("Error")
},
processData: false,
async: true
});
});
});
Instead of returning the data you will have to return the view as string and the use jquery to replace the result.
Controller:
public JsonResult About()
{
var model = // Your Model
return Json((RenderRazorViewToString("ViewNameYouWantToReturn", model)), JsonRequestBehavior.AllowGet);
}
[NonAction]
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Then using jquery you can replace the result in container for eg: div as follows:
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (result) {
$("#divId").replaceWith(result);
},

Print out to a div in the view from the controller

I have a div block in my view like this:
<div id="divStatus" style="margin-top:10px;width: 200px; height: 100px; overflow-y: scroll;">
</div>
then from the view, user clicks on a button that calls the controller. In the controller some tasks are executed so from the controller I want to update a div block within the view. In this div I print out phrasses.
How to do this?
example:
public ActionResult()
{
// Do something
Update_DIV_in_View("some thing has been done"); <--- DIV in the view must be updated by appending this message
// Do another thing
Update_DIV_in_VIEW("another thing has been done");<--- DIV in the view must be updated by appending this message
.... and so on
// All things done
Update_DIV_in_VIEW("All things have been done");<--- DIV in the view must be updated by appending this message
return View();
}
Create a second action in your controller which only shows the updated content of the div and on your normal page when you press the button load the status with an AJAX call (for example the jQuery.load() method).
You can do it as follows:
In your view use Ajax Form as follows:
#using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions { OnBegin = "beforeSubmitFunction()", HttpMethod = "POST",UpdateTargetId = "divStatus", OnComplete = "InsertRow()" }))
{
.. //your Html form Controls
}
function beforeSubmitFunction()
{
//Your code for before submitting...
}
Then in your controller return your partial view as result which will get updated in your div with id divStatus
[HttpPost]
public ActionResult Index(TypeName model)
{
return PartialView("PartialViewName", model);
}
Here are 3 examples what I am using:
example 1:
button (here with telerik css styling):
<a class="t-button t-button-icontext" onclick="ajaxCreateEquipment()"><span
class="t-icon t-add"></span>Create</a>
javascript: #equipment-table-container is the id of the target div:
<script type="text/javascript">
function ajaxCreateEquipment() {
$.ajax({
type: 'GET',
url: '#Url.Action("ShowCreate", "Equipment")',
dataType: 'html',
success: function (data) {
$('#equipment-table-container').html(data);
}
});
}
</script>
EquipmentController.cs:
[HttpGet]
public ActionResult ShowCreate()
{
// some calculation code, fetch model from DB something else
ViewData.Add("FormAction", "Create"); // some ViewData
return PartialView("Create", model); // returns the View html file
}
example 2:
function call here with id argument and Json return:
#{
var supplierQuoteId = Model.ID.ToString();
<a id="#supplierQuoteId" onclick="updateDiv(this.id)"></a>
}
javascript:
function updateDiv(id) {
var strUrl = "/LicenseTerm/UpdateUsedQuantity/" + id;
$.ajax({
type: "GET",
url: strUrl,
cache: false,
dataType: "json",
success: function (data) {
$('#licenseterm-usedquantity').html(data.sum);
}
});
}
LicenseTermController.cs
[HttpGet]
public JsonResult UpdateUsedQuantity(Guid id)
{
var licenseTerm = _repository.GetAll<LicenseTerm>().Where(l => l.ID == id).First();
int sum = 0;
foreach (LicenseAllocation l in licenseTerm.LicenseAllocations.Where(o => o.Deleted == false))
sum = sum + l.LicenseQuantity;
return Json(new { sum = sum }, JsonRequestBehavior.AllowGet);
}
example 3: simple get
function ajaxFieldDefinitionCreate(id) {
var strUrl = '/FieldDefinition/Create' + '/' + id.toString() + '?isRefreshAction=true';
$.get(strUrl, function (data) {
$('#equipmenttype-fielddefinition-createeditarea').html(data);
});
}
[HttpGet]
public ActionResult Create(Guid id, [Optional, DefaultParameterValue(false)] bool isRefreshAction)
{
var equipmentType = _equipmentTypeRepository.GetById(id);
var fieldDefinitionDto = new FieldDefinitionDto
{
ID = Guid.NewGuid(),
ParentName = equipmentType.Name,
};
return PartialView("Create", fieldDefinitionDto);
}
In response to the changes of the question, especially that the questioner would like to have more returns in the same Action:
the concept of HTTP request is to transmit relatively small pieces of data from the server to the client, which invoked the e.g. HTTP GET request.
You can not keep open the HTTP GET request for more transmissions.
I searched the web and extracted that especially HTML5 will address this requirement with the HTTP stream, but this is another topic. e.g.: I got this url: http://socket.io/ .
Bypass:
But as an idea of mine,
I would make a first ajax call to determine the count of the next requests, addressed in the controller Action1.
And then invoke several new requests in the success part of the first ajax request, with the url of the Action2, e.g. Calculate etc., which appends then the several pieces of data to the div content.
here some quickly invented javascript code:
function updateDiv() {
var strUrl = "/Home/RequestCount/";
$.ajax({
type: "GET",
url: strUrl,
cache: false,
dataType: "json",
success: function (count) {
var strUrlCalc = "/Home/Calc/";
for (var i = 0; i < count; i++) {
$.ajax({
type: "GET",
url: strUrlCalc,
cache: false,
dataType: "json",
success: function (data) {
$('#test').append(data);
}
});
}
}
});
}

ActionLink to HttpPost action method

I have this link on my page:
#Html.ActionLink("Like", "Like", "Like", new {likeId = i.ItemId}, new {id = #i.ItemId, #class = "likeButton"})
This is my ajax call:
$(document).on("click", ".likeButton", function (event) {
var itemId = event.target.id;
$.ajax({
url: this.href,
type: 'POST',
data: { item: itemId },
context: this,
success: function (result) {
...
return false;
});
And it works when action metohd is like:
public ActionResult Like(int itemId)
...
But if I decorate method with [HttpPost] It doesn't work.
Can this be achieved?
Also what security issue can be if I don't add [HttpPost]?
Try this:
$(document).on("click", ".likeButton", function (event) {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
...
return false;
});
You are passing item.Id twice, first in url and second in body. when using post method, you can still pass parameters through url. passing parameters with body is good when you want to hide these parameters.
And one more thing, you can use Ajax.ActionLink in this case (because it is created for this kind of cases)
And you have mistake:
data: { item: itemId }
Should be:
data: { itemId: itemId },

JQUERY ajax passing null value from MVC View to Controller

hi guys i'm posting some data to controller using jquery ajax, but i am getting null values in my controller,
jQuery code is:
$('#registerCompOff').click(function() {
var compOff = [];
$('div').each(function() {
var curRow = {};
curRow.Description = $(this).find('.reason').val();
curRow.CompOffDate = $(this).find('.datefieldWithWeekends').val();
if (curRow.Description != null && curRow.CompOffDate != null) {
compOff.push(curRow);
}
});
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
data: compOff
});
return $('form').valid();
});​
compOff is not null I have checked that...
controller is:
[HttpPost]
public ActionResult RegisterCompOff(RegisterCompOff[] registerCompOff)
{
//return View();
}
can you tell me where i'm going wrong?
Given your original code, change in $.ajax -> data: JSON.stringify(compOff) then add contentType: "application/json; charset=utf-8" and finally change parameter name of controller's action to public ActionResult RegisterCompOff(RegisterCompOff[] compOff). Model binding should kick off then. It did for me.
Edited:
try this :
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
traditional: true,
data:
{
CompOffList: compOff
}
});
and change your controller like this :
[HttpPost]
public ActionResult RegisterCompOff(List<RegisterCompOff> CompOffList)
{
//return View();
}
hope this helps
Your r passing javascript object as data wherease jquery ajax method expects a key/value pair list.
Try this
data:{Description:compOff.Description, CompOffDate:compOff.CompOffDate}

Resources