MVC: Result from JSON Automatically fill View - asp.net-mvc

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);
},

Related

Partial View not showing updated model values. Always shows existing values

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) {
}
});

how to update different Partial view using one ajax call

In above image when double click on div(First Image) then View dialog box(second Image) both case content printed same data but structure is different.
controller
[HttpPost]
public ActionResult FirstParialView(long ID)
{
//inserted some data into database Here
List<TimetableDetails> timetableObs =unitofWork.TimetableDetails.ToList();
return PartialView("DayStructure/_FirstView", timetableObs);
}
[HttpPost]
public ActionResult SecondParialView(long ID)
{
List<TimetableDetails> timetableObs =unitofWork.TimetableDetails.ToList();
return PartialView("DayStructure/_SecondView", timetableObs);
}
Ajax call (This Ajax design and work in dialog box)
#using (Ajax.BeginForm("FirstParialView", "timetable", new { area = "User" },
new AjaxOptions { OnSuccess = "ViewMPlan"))
{
//Inserted Some data using submit button here. and view both parial view
}
javascript
function ViewMPlan(response) {
//print first Parial View
$('#firstParialView').html(response);
//for second parial view
$.ajax({
url: "/user/timetable/SecondParialView",
type: "POST",
dataType: "JSON",
data: { ID: ID},
success: function (response) {
$('#SecondParialView').html(response);
}
});
}
In above case I have to seperate ajax call for second parial view actual it gets same data .
Is this possible to update both parial View using just Single Call like just Only calling FirstParialView
You you can indeed do this what i do is that i'v created a function which will render my partial views inside a variable, like this
private string RenderPartialView(string viewName, object model)
{
ViewData.Model = model;
using (System.IO.StringWriter writer = new System.IO.StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, writer);
viewResult.View.Render(viewContext, writer);
return writer.GetStringBuilder().ToString();
}
}
now you need to change your action result something like
[HttpPost]
public JsonResult AjaxCallFunc(long ID)
{
List<TimetableDetails> timetableObs =unitofWork.TimetableDetails.ToList();
var partialView1 = RenderPartialView("DayStructure/_FirstView", timetableObs);
var partialView2 = RenderPartialView("DayStructure/_SecondView", timetableObs);
return Json(new{View1=partialView1,View2=partialView2 },JsonRequestBehaviour.DenyGet);
}
and then your controller to
unction ViewMPlan(response) {
//print first Parial View
$('#firstParialView').html(response);
//for second parial view
$.ajax({
url: "/user/timetable/AjaxCallFunc",
type: "POST",
dataType: "JSON",
data: { ID: ID},
success: function (response) {
$('#FirstPartialView').html(response.View1);
$('#SecondParialView').html(response.View2);
}
});
}

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

How to pass a object from ajax to the server in MVC?

I've got two models, there are.
public class CreateAssignmentViewModel {
...
public List<CreateAssignmentSelectedItem> SelectedItems { get; set; }
}
public class CreateAssignmentSelectedItem {
...
}
Now I've got a view where contains CreateAssignmentViewModel, as you can see above this class contains a property where is a List<CreateAssignmentSelectedItem>
#model Contoso.MvcApplication.Models.Assignment.CreateAssignmentViewModel
#{
ViewBag.Title = "Create Assignment";
...
}
#using (Html.BeginForm()) {
...
}
Inside of the Html.BeginForm, I've got a partial view. And in it I've got a button using ajax where updates the partial view.
Look the following events. Where says data: I do not know what to enter to access only the property SelectedItems
var addQuestionToAssignmentContent = function (questionId)
{
$.ajax({
url: "/Assignment/AddItemToAssignmentContent",
type: "post",
data: { model: $(this).serialize() /* HERE I DON'T KNOW TO ACCESS THE */, itemId: questionId },
success: function (response) {
var $target = $("#assignmentContent");
var $newHtml = response;
$target.replaceWith($newHtml);
}
});
};
public ActionResult AddItemToAssignmentContent(List<CreateAssignmentSelectedItem> model, string itemId)
{
...
PartialView(..);
}
How can I do to pass only the object in the method?
First, give your form an ID:
#using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new{id = "frmUpdate"})) {
Second, change your code to be like this:
var f = $("#frmUpdate");
$.ajax({
url: f.attr('action'),
type: f.attr('method'),
data: f.serialize(),
//etc..
I use this in most cases and it works just nice. The data should automatically be bound to the model you have in your update action. So, for example... if you have a #model of type MyModel then in the update action it should look something like this:
[HttpPost]
public ActionResult Update(MyModel updatedModel)
Sometimes I work with a front end guy and he might not adhere to pass in the correct model, he might change the form fields or whatever. In this case I just let him serialize the form and pass it to the action an any way he wants.
I then use the FormCollection object to get the data I need.
Your json call
var addQuestionToAssignmentContent = function (questionId)
{
$.ajax({
url: "/Assignment/AddItemToAssignmentContent",
type: "post",
data: { model: $(this).serialize() /* HERE I DON'T KNOW TO ACCESS THE */, itemId: questionId },
success: function (response) {
var $target = $("#assignmentContent");
var $newHtml = response;
$target.replaceWith($newHtml);
}
});
};
Get a form collection object
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItemToAssignmentContent(FormCollection collection)
{
vars someValue = collection.GetValue("somefield").AttemptedValue;
}
But if I would have control of front-end as you do then as Matt suggested you should use an pass a model;

MVC ViewModel issue

I have a viewmodel that has 2 properties, first property is a Model object and the second property is a List . In my View i have 2 parts.
First part populates the data for the first object, Firstname,lastname,email and some other stuff.
The second part of my view is a webgrid that a user adds multiple address.
Now what is my problem, i have a JSON action on my controller that gets the data from the form, adds them to the viewmodel List property, but nothing happens.
I checked that the data is coming from the view, added to the viewmodel but each time the viewmodel is empty.
[Authorize]
public JsonResult addAddress(Address addr, CustomerViewModel model)
{
if (model.CAddress== null)
model.CAddress= new List<Address>();
model.CAddress.Add(addr);
return Json(model, JsonRequestBehavior.AllowGet);
}
I am using Javascript :
function AddAddress()
{
var addID = $("#lstID option:selected").val();
var addName = $("#lstAddName option:selected").text();
var Address =
{
addID : addID.toString(),
addName : addName.toString()
};
$.ajax({
type: "POST",
url: "#Url.Action("addAddress","Customer")",
dataType: "json", contentType: "application/json; charset=utf-8",
data: JSON.stringify(Address),
success: function (data) {} }); };
Alright, start by writing a real view model, not some hybrids:
public class CustomerViewModel
{
public List<AddressViewModel> Addresses { get; set; }
... some other properties you already had
}
public class AddressViewModel
{
public string Id { get; set; }
public string Name { get; set; }
}
then adapt your controller action to take your real view model, and not some hybrids and mixtures between view models and domain models:
[Authorize]
[HttpPost]
public ActionResult AddAddress(CustomerViewModel model)
{
return Json(model);
}
and finally adapt your AJAX call:
function AddAddress() {
$.ajax({
url: '#Url.Action("AddAddress", "Customer")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
addresses: [
{
id : $('#lstID').val(),
name : $('#lstAddName option:selected').text()
}
],
someOtherPropertyOnYourViewModel: 'some other value'
}),
success: function (data) {
}
});
}

Resources