how to update different Partial view using one ajax call - asp.net-mvc

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

Related

How to pass JSON data (list created using Jquery) to an action in controller in MVC?

I have a function in jquery which creates a list of values being selected from a checkbox. Now I want to have this list in my controller action. I have converted this list to JSON but I am not able to pass it to the controller. I also tried creating a custom model corresponding to the json data.
Jquery Code
$("button").click(function () {
//alert("clicked");
var obj = {};
//var tempRadio = [];
for (var i = 1; i <= globalVar; i++) {
if ($("#" + i).prop("checked") == true) {
obj[i] = $('input[class=' + i + ']:checked').val();
}
}
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SkillAdd","User")',
data: JSON.stringify(obj),
//data: hello,
error:function ()
{
alert("Error");
},
success: function () {
alert(JSON.stringify(obj));
}
});
});
Controller Code
public ActionResult SkillAdd(List<string> Id, List<string> Name)
{
return View();
}
Controller Code with Custom Model
public ActionResult SkillAdd(List<MyModel> object)
{
return View();
}
You have an object in javascript but you need to create an array so that it can be mapped to List at post. So change your js code to be :
var obj = []; // it's array now
and then you will add items in it like in your loop:
obj.push( $('input[class=' + i + ']:checked').val());
and in your ajax call name the parameter what you have in your controller action:
data:{ Id : obj }
and now you can have a parameter in action method List<string> which would hold the data posted by ajax call.
public ActionResult SkillAdd(List<string> Id)
{
return View();
}
Hope it helps.

mvc display text after post and keep data in form

How can I after posting a form in my mvc page display a message and keeping the added/selected data in the form? I have tried to render a partialview but that renders a blank page which only contains the actual partialview.
<div id="resultTarget">
#Html.Partial("CalculationResult", new Model.CalculatedPrice())
</div>
[HttpPost]
public PartialViewResult GetPrice(FormCollection formCollection)
{
// This renders only the partialview
return PartialView("CalculationResult", model);
}
If you reload the page with a form post the data will be lost. Create a view model and bind the controls to specific properties using #Html.TextBoxFor(), #Html.ListBoxFor() etc.
Now instead of submitting the form back to the controller, use javascript to post data back to the controller on a button click function.
See below code :
In Button Click function :
var modelObj = {};
modelObj.prop1 = $('#txtField1').val();
modelObj.prop2 = $('#txtField2').val();
var postObj = JSON.stringify(modelObj); // convert object to json
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "/SomeController/GetPrice",
data: { formCollection: postObj }
cache: false,
success: function (data) {
if (data) {
//Some Code if post success
}
else {
// Some code if post failed
}
}});
In SomeController :
[HttpPost]
public JSonResult GetPrice(FormCollection formCollection)
{
// Do your action with the formCollection object here
// if(action.success)
{
return JSon(true);
}
return JSon(false);
}
This way you can prevent reloading of the page and keep the data in the forms as such.

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

How pass int list from action to view, then from view to method in mvc 4?

In MVC4 application in Create(post) action I want to pass int type list to view if error occur. And then, from there to pass it to other method in same controller with ajax post. So, TempData, ViewData and ViewBag don't help me.
public ActionResult Create(CreateModel model)
{
if(hasCustomError)
{
List<int> selectedItems = new List<int>() { 1, 2, 8 }; //for example.
ViewBag.VB = selectedItems;
//ViewData["VD"] = selectedItems;
//TempData["TD"] = selectedItems;
return View(model);
}
return RedirectToAction("Index");
}
After return View(model);, list of selectedItems passed to Create.cshtml view. It has value here I checked. But from here I should pass that list to GetTreeData method via ajax post:
#{
if (ViewBag.VB != null)
{
TempData["SelectedItems"] = ViewBag.VB as List<int>;
}
}
$("#myTree").jstree({
json_data: {
"ajax": {
url: "#Url.Action("GetTreeData", "MyController")",
type: "POST",
dataType: "json",
contentType: "application/json charset=utf-8"
}
},
checkbox: {
real_checkboxes: true,
checked_parent_open: true
},
plugins: ["themes", "json_data", "ui", "checkbox"]
});
In the MyController, in GetTreeData method TempData["SelectedItems"] is null .
public string GetTreeData()
{
List<int> selecteds = null;
if (TempData["SelectedItems"] != null)
{
selecteds = TempData["SelectedItems"] as List<int>;
TempData["SelectedItems"] = null;
}
......................................
}
I tried this for all (TempData, ViewData and ViewBag). nothing changed.
How can pass that list from action to view and then from that view to method?
Create a viewmodel, in that viewmodel set your model that you are using now as a field, and add an extra field for that list

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;

Resources