Rendering Partial View in a div dynamically in mvc3 - asp.net-mvc-3

I have a list of link buttons(l1,l2,l3..etc) and a fixed div area.when I click l1 for example partialview1 will populate within div and when I click l2 for example partialview2 will populate within the same div replacing existing partialview1.Each partial view has different model.
My Code is given below: SettingsMaster.cshtml
#{
ViewBag.Title = "ManageSettings";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/SettingsCustomScript.js")"></script>
}
<h2>ManageSettings</h2>
#Html.ActionLink("Area", null, null, null, new {#id="Area", #style = "text-transform:capitalize;" })
#Html.ActionLink("Subarea", null, null, null, new {#id="SubArea", #style = "text-transform:capitalize;" })
<div id="Datadisplay"></div>
Java Script Code:Custom Javascript file
/// <reference path="jquery-1.8.3.js" />
/// <reference path="jquery-1.5.1-vsdoc.js" />
$(document).ready(function () {
$("#Area").click(function () {
$("#Datadisplay").load('/Settings/GetArea', null, function (response, status, xhr) {
if (status == "error") {
alert("An error occured");
}
return false;
});
});
$("#Subarea").click(function () {
alert("hello");
}
);
Controller Method:
public class SettingsController : Controller { // // GET: /Settings/
[HttpGet]
public ActionResult ManageSettings()
{
return View();
}
[HttpGet]
public ActionResult GetArea()
{
return PartialView("GetArea");
}
}
But when it is rendering it is calling ManageSettings() this is why it is not showing. Plz help me what to do

I read this in another post in stack overflow and it worked for me
in the View:
#model Tuple<IEnumerable<Model1name>,Model2name>
#foreach (var item in Model.Item1)
{
#item.Name
}
In the Controller:
var tuple = new Tuple<IEnumerable<Model1name>, Model2name>(context.Model1name.ToList(), new Model2name());
return View(tuple);

Use a simple jquery call.
On the click of your link buttons you do a $.Get(...) and render the partialview returned by your controller

Related

How to get selected Drop down list value in view part of MVC?

I want to pass selected Drop down list value to Ajax Action Link which is I am using in Controller. Every time When I will change drop down list value. I want that respective value pass to the action link.
What I need to write here in Ajax Action Link ????
Drop Down List
<div class="form-group">
#Html.DropDownListFor(model => model.ComponentId, ((List<string>)ViewBag.Cdll).Select(model => new SelectListItem { Text = model, Value = model }), " -----Select Id----- ", new { onchange = "Action(this.value);", #class = "form-control" })
</div>
Ajax Action Link
<div data-toggle="collapse">
#Ajax.ActionLink("Accessory List", "_AccessoryList", new { ComponentId = ???? }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divacc",
InsertionMode = InsertionMode.Replace
})
</div>
Controller
public PartialViewResult _AccessoryList(string ComponentId)
{
List<ComponentModule> li = new List<ComponentModule>();
// Code
return PartialView("_AccessoryList", li);
}
Here is a new post. I do dropdowns a little different than you, so I am showing you how I do it. When you ask what to pass, I am showing you how to pass the dropdown for 'component' being passed. I also show how to pass from ajax back to the page.
Controller/Model:
//You can put this in a model folder
public class ViewModel
{
public ViewModel()
{
ComponentList = new List<SelectListItem>();
SelectListItem sli = new SelectListItem { Text = "component1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "component2", Value = "2" };
ComponentList.Add(sli);
ComponentList.Add(sli2);
}
public List<SelectListItem> ComponentList { get; set; }
public int ComponentId { get; set; }
}
public class PassDDLView
{
public string ddlValue { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostDDL(PassDDLView passDDLView)
{
//put a breakpoint here to see the ddl value in passDDLView
ViewModel vm = new ViewModel();
return Json(new
{
Component = "AComponent"
}
, #"application/json");
}
public ActionResult IndexValid8()
{
ViewModel vm = new ViewModel();
return View(vm);
}
View:
#model Testy20161006.Controllers.ViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid8</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function () {
var PassDDLView = { ddlValue: $("#passThis").val() };
$.ajax({
url: '#Url.Action("PostDDL")',
type: 'POST',
data: PassDDLView,
success: function (result) {
alert(result.Component);
},
error: function (result) {
alert('Error');
}
});
})
})
</script>
</head>
<body>
<div class="form-group">
#Html.DropDownListFor(m => m.ComponentId,
new SelectList(Model.ComponentList, "Value", "Text"), new { id = "passThis" })
<input type="button" id="btnClick" value="submitToAjax" />
</div>
</body>
</html>

mvc5 ajax not refreshing Partial View

I am having a View which contains a textbox, a button and a virtual book in a partial view. After Pressing the button, the text from the textbox is placed on the first page of the book and then the book (the partial view) should be refreshed.
With the Ajax I can call the method PlaceText (which place a text on the first page/image of the book) but it doesn't refresh the partial view _Book.
I tried
$("#services").load("_Book");
and
$("#services").load("PlaceText");
and many more things after reading these solutions for a similar problem, but nothing seems to work. The allert("ok") appears, but the partialView doesn't refresh
<script type ="text/javascript">
$(document).ready(function(){
$("#myLink").click(function (e) {
e.preventDefault();
var textboxvalue = $('input[name=your-name]').val();
$.ajax({
data: { name: textboxvalue },
type: 'POST',
url: '#Url.Action("PlaceText", "Home")',
success: function (result) {
$("#services").html("_Book");
alert("ok");
}
});
});
});
</script>
#Html.ActionLink("Mehet", "PlaceText", null, new { id = "myLink" })
This is my Controller:
[HttpPost]
[OutputCache(Duration = 0)]
public ActionResult PlaceText(string name)
{
PointF firstLocation = new PointF(700f, 80f);
string imageFilePath = Server.MapPath(#"~/images/demo1/elolap3.jpg");
string imageFilePath2 = Server.MapPath(#"~/images/demo1/elolap1.jpg");
Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file
using (Graphics graphics = Graphics.FromImage(bitmap))
{
using (Font arialFont = new Font("Bigfish", 40))
{
graphics.DrawString(name, arialFont, Brushes.Blue, firstLocation);
}
}
bitmap.Save(imageFilePath2);//save the image file
return PartialView("_Book", db.imageModel.ToList());
}
This is my view (Index):
<section id="services" class="services service-section">
#Html.Partial("_Book");
</section>
My partial view:
<div class="Heidelberg-Book with-Spreads" id="Heidelberg-example-1">
#foreach (var image in Model)
{
<div class="Heidelberg-Spread">
<img src="#Url.Content(image.FilePath)" />
</div>
}
</div>

View not rendering after foreach loop MVC

Goal: I am attempting to populate a table based on a dropdown list using Razor syntax to populate my table.
Summary: I am passing the model into my View and looping thru each object within my model. I am able to see the objects populated within the model when debugging the View, however, when the page actually displays, There is nothing in the table and the only thing that is displaying is the dropdown.
Question: What may be the problem with the page rendering?
My view is as follows:
#model IEnumerable<FantasySportsMVC.Models.PlayerDetails>
#{
ViewBag.Title = "Position";
}
<h2>Position</h2>
<body>
<div>
#Html.DropDownList("ddlTournaments",(IEnumerable<SelectListItem>)ViewBag.Tournaments, new { id="ddlTournament", name="ddlTournament"})
</div>
<div>
<input type="button" id="btnGetData" value="Show me some stuff, Yo!" />
</div>
<div id="results">
</div>
<table id="tbDetails">
#if(Model != null)
{
<tbody>
#foreach (var player in Model)
{
<tr>
<td>#player.LastName</td>
<td>#player.FirstName</td>
<td>#player.Position</td>
</tr>
}
</tbody>
}
</table>
</body>
<script type="text/javascript">
function SendTournamentId() {
var data = JSON.stringify({ id : $("#ddlTournament option:selected").val()});
$.ajax({
url: '/Leaderboard/Position',
type: 'POST',
dataType: 'json',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (result) {
//return JSON.stringify($("#ddlTournament option:selected").val());
$("#ddlTournament option:selected").val(result.d.id);
}
});
}
$(function () {
$('#btnGetData').click(SendTournamentId);
});
</script>
My Controller is as follows:
public class LeaderboardController : Controller
{
public ActionResult Position()
{
ViewBag.Tournaments = GetTournamentDetailsSelectList();
return View();
}
[HttpPost]
public ActionResult Position(string id)
{
ViewBag.Tournaments = GetTournamentDetailsSelectList();
var tournamentId = id;
var url = ConstructLeaderboardUrl(tournamentId);
var xmlToJsonUrl = ConvertXmltoJson(url);
List<PlayerDetails> details = BindDataTablePlayerDetails(xmlToJsonUrl);
return View(details);
}
}
private static List<PlayerDetails> BindDataTablePlayerDetails(string url)
{
dtAttributeList = new DataTable();
var details = new List<PlayerDetails>();
try
{
//ConvertXmltoJson(url);
// Construct Datatable
dtAttributeList.Columns.Add("Last Name", typeof(string));
dtAttributeList.Columns.Add("First Name", typeof(string));
dtAttributeList.Columns.Add("Position", typeof(string));
// Add rows to Datatable from Json
for (int i = 0; i < doc.GetElementsByTagName("player").Count; i++)
{
dtAttributeList.Rows.Add(
doc.GetElementsByTagName("player").Item(i).Attributes["last_name"].Value,
doc.GetElementsByTagName("player").Item(i).Attributes["first_name"].Value,
doc.GetElementsByTagName("player").Item(i).Attributes["position"].Value);
}
// Add rows from Datatable to PlayerDetails
foreach (DataRow row in dtAttributeList.Rows)
{
var player = new PlayerDetails();
player.LastName = row["Last Name"].ToString();
player.FirstName = row["First Name"].ToString();
player.Position = row["Position"].ToString();
details.Add(player);
}
}
catch (Exception e)
{
throw new Exception();
}
return details;
}

MVC3 ajax return new view

I have some code which displays a dropbox with a list of entries from a database and calls a controller action on the change event. The controller takes the selected entry as a string and returns a new view (I think herein lies my issue), the trouble is I think that the old view still remains as the newly returned view is never displayed.
Do I need to redesign this or if not, should I be forcibly destroying any old view?
My code is as follows:
EditSchool view:
#model namespace.Models.SchoolDetails
#{
ViewBag.Title = "EditSchool";
Layout = "~/Views/AuthorisedAdmin/_LayoutAdmin.cshtml";
}
<script src="#Url.Content("~/Scripts/chosen/chosen.jquery.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/bubble-popup-chosen-upload-functions.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#School").change(function () {
var SelectedSchool = $('#School').val();
$.ajax({
url: '/AuthorisedAdmin/RetrieveSchool'
, type: 'POST'
, data: { School: SelectedSchool }
, success: function (data) {
}
, error: function (request, textStatus, errorThrown) {
alert(errorThrown.toString());
}
, complete: function (request, textStatus) {
}
});
});
});
</script>
<fieldset>
<legend>Select School</legend>
<div class="editor-field">
#Html.DropDownList("School", ViewBag.RegisteredSchools as SelectList, namespace.Models.Helpers.LanguageSchoolsConstants.m_sDropdownDisplayText,
new
{
id = "School",
#class = "chosen",
})
</div>
</fieldset>
#{
if (null != Model)
{
#Html.Partial("Partial/EditSchoolPartial", Model)
}
else
{
#Html.Partial("Partial/NoSchoolSelected")
}
}
Note that the partial view (EditSchoolPartial) is probably not a concern here, so I'm not posting the code.
Controller methods of interest:
EditSchool action:
public ActionResult EditSchool()
{
List<string>kRegisteredSchools = DBHelperFunctionsSchool.Instance().GetRegisteredSchoolsNamesOnly();
ViewBag.RegisteredSchools = new SelectList(kRegisteredSchools, "Name");
SchoolDetails schoolDetails = null;//DBHelperFunctionsSchool.Instance().GetSchoolDetailsForName(kRegisteredSchools.FirstOrDefault());
return View(schoolDetails);
}
RetrieveSchool action (called by AJAX):
[HttpPost]
public ActionResult RetrieveSchool(string School)
{
SchoolDetails schoolDetails = null;
List<string> kRegisteredSchools = DBHelperFunctionsSchool.Instance().GetRegisteredSchoolsNamesOnly();
ViewBag.RegisteredSchools = new SelectList(kRegisteredSchools, "Name");
try
{
schoolDetails = new SchoolDetails();
schoolDetails.School = DBHelperFunctionsSchool.Instance().GetSchoolForName(School);
DBHelperFunctionsSchool.Instance().PopulateSchoolDetailsSuppData(schoolDetails);
schoolDetails.ActionNameToExecuteOnFormSubmit = "EditSchoolDetails";
schoolDetails.ControllerNameToExecuteOnFormSubmit = "AuthorisedAdmin";
}
catch
{
schoolDetails = null;
}
finally
{
}
return View("EditSchool", schoolDetails);
}
Instead of doing ajax on onchange ,do below
$("#School").change(function () {
var SelectedSchool = $('#School').val();
window.location='/AuthorisedAdmin/RetrieveSchool?School='+SelectedSchool;
});
Note:You may have to give full path url instead of relative url.

How to use ajax call to pass json data to controller and render a partial view as result?

I need to pass model object to controller, and from there to call service to generate data for the partial view. I am able to pass the json object to the main view, and I am able to generate the partial view. However, I am having difficulties to render the partial view in the main view after the call. If I don't pass object to controller, I am able to render the partial view.
My Main goal is: to pass json object and render partial view with the same ajax call.
Would appreciate help on this.
I apologize for the lengthy code here, but not sure how I could do it some other way.
The following code works, where I do not pass Json object via ajax call, and create department object in the controller:
main view code:
#model PartialViewDemo.Models.School
....
<body>
....
<div>
#Html.Partial("_MyPartialView", Model.Department )
</div>
....
<div id="divTest"></div>
<input type="button" value="Click" id="btnClick"/>
</body>
<script src="~/Content/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#btnClick').click(function(data) {
var dept = {
DepartmentName: "test Dept",
DepartmentRule: "test rule",
Comment:" test comment"
};
$.ajax({
url: '/home/ShowPartailView/',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
});
</script>
controller code:
public ActionResult Index()
{
var model = new School();
model.Department = GetDepartmentList(3);
return View(model);
}
public List<Department> GetDepartmentList(int counter)
{
var model = new List<Department>();
for (var i = 1; i <= counter; i++)
{
var data = new Department();
data.DepartmentName = "Dept " + i;
data.DepartmentRule = "Rule " + i;
data.Comment = "Comment " + i;
model.Add(data);
}
return model;
}
public PartialViewResult ShowPartailView()
{
Department dept = new Department()
{
DepartmentName = "test Dept",
DepartmentRule = "test rule",
Comment = "We Rock!"
};
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
Partial view code:
#model PartialViewDemo.Models.Department
<h2>_MyView from partial view using PartialView</h2>
#if (Model != null)
{
<div>
<table>
<thead>
....
</thead>
<tbody>
<tr>
<td>#Model.DepartmentName</td>
<td>#Model.DepartmentRule</td>
<td>#Model.Comment</td>
</tr>
</tbody>
</table>
</div>
}
Model:
public class Department
{
public string DepartmentName { get; set; }
public string DepartmentRule { get; set; }
public string Comment { get; set; }
}
public class School
{
public List<Department> Department { get; set; }
}
However, when I pass in Json object to ajax call with all other code stay the same, except the following changes, the partial view won't show with click event.
$.ajax({
url: '/home/ShowPartailView/',
data: JSON.stringify(dept),
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
with controller code:
public PartialViewResult ShowPartailView(Department dept)
{
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
In the second example where you pass the object, you have specified the
dataType: 'json',
ajax option but your controller method is returning a partial view so it needs to be
dataType: 'html',
Side note: You can omit the contentType option and just use data: dept,
If you have return partial view then try this to render partial view in Div or any other element.
$(document).ready(function () {
$.ajax({
url: '/YourContollerName/YourActionName',
type: "POST"
})
.success(function (result) {
$('.loadOnDivClass').empty();
$('.loadOnDivClass').html(result);
})
.error(function (status) {
alert(status);
})
});
If Contrller Action return like this
return PartialView("_PartialList",modelObj);

Resources