I have a simple list view where I'm loading my data.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Your application description page.";
IList<Product> products;
using (ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
products = session.Query<Product>().ToList(); // Querying to get all the books
}
return View(products);
}
}
View is a simple list view from template.
Now, I need to load data to list view just after button click.
So as I understand I need to render partial view.
I've add this to view:
<button id="Load">Load data</button>
<script type="text/javascript">
var url = '#Url.Action("LoadData", "Home")';
$('#Load').click(function() {
var keyWord = $('#Keyword').val();
$('#result').load(url);
})
</script>
<div id="result"></div>
And add controller action:
public ActionResult LoadData()
{
// here will be model creation and passing view
return PartialView();
}
But controller action doesn't get called.
What should I do?
This is now I would do it.
We create an action method which return JSON on http gets
public class SomeController : Controller
[HttpGet]
public ActionResult LoadData()
{
using (ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
products = session.Query<Product>().ToList(); // Querying to get all the books
}
return Json(new {data=product},
JsonRequestBehavior.AllowGet);
}
Inside your view we do a ajax request to get the data by calling LoadData
$.ajax({
type: 'get',
dataType: 'json',
url: 'SomeController/LoadData',
success: function (data) {
//Render data to view maybe using jquery etc
},
error: function(data) {
//Notify user of error
}
});
Hope this helps man
Related
I am trying to reload my Partial View _Home when I close my dropdown. Currently I can get that dropdown value to call another method and do the logic that will change the model then send the model back to the index. However, I cannot get my _Home Partial View to reload and actually take in this new model. I cannot seem to be able to actually call the public ActionResult _Home(Model model) method. I am wondering how to pass in this new model and refresh the partial view.
I have tried to pass in the model to the partial view but this seems to have no effect, having no model being passed in does not change anything either. I have seen a few examples online of how to refresh partial views but none of them pass in any parameters.
JavaScript
function OnClose() {
var chart = $("#safetyIncident-chart").data("kendoChart");
var chart2 = $("#qualityError-chart").data("kendoChart");
chart.dataSource.read();
chart2.dataSource.read();
var selectProductionLine = $("#productionLine-dropdown").data("kendoDropDownList").value();
$.ajax({
url: '#Url.Action("UpdateView", "Home")', //Updates model and then calls Index
type: 'post',
dataType: "json",
data: { "selectProductionLine": JSON.stringify(selectProductionLine) }, //Passes in DropDownValue correctly
success: function (data) {
$("#partial").html(result);
$("#Dashboard").load("/Home/_Home"); //Trying to reload the partial view
}
});
}
View
<div id="Dashboard">
#Html.Partial("~/Views/Home/_Home.cshtml")
</div>
Controller
[HttpGet]
public ActionResult Index()
{
DisplayViewModel dvm = (DisplayViewModel)TempData["dvm"];
if(dvm != null)
{
return View(dvm);
}
//Initializes new dvm if previous was null
return View(dvm);
}
I am trying to refresh my partial view once DropDown closes and the ViewModel is refreshed.
EDIT:
UpdateView method in Controller
[HttpPost]
public ActionResult UpdateView(string selectProductionLine)
{
if(selectProductionLine == null)
{
selectProductionLine = _productionLineService.Collection().FirstOrDefault().Id;
}
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(selectProductionLine, typeof(string));
DisplayViewModel dvm = new DisplayViewModel();
ProductionLine pl = _productionLineService.Find(jsondata);
dvm.ProdLine = new ProductionLineViewModel
{
Id = pl.Id,
CreatedAt = pl.CreatedAt,
Name = pl.Name,
ActiveLine = pl.ActiveLine,
ComputerName = pl.ComputerName,
UPE = pl.UPE
};
TempData["dvm"] = dvm;
return Index();
//PartialView("~/Home/_Home.cshtml", dvm);
}
I had a perfectly working system showing recently entered data on a grid as soon as i saved the data. after using ajax the data is entered but the newly entered data is shown if i reload the page.
On Controller:
[HttpGet]
public ActionResult Index()
{
RoleBusinessLayer roleBusinessLayer = new RoleBusinessLayer();
List<Role> roles = roleBusinessLayer.Roles.ToList();
ViewBag.Roles = roles;
return View();
}
[HttpPost]
public ActionResult Index(Role role)
{
if(ModelState.IsValid)
{
RoleBusinessLayer roleBusinessLayer = new RoleBusinessLayer();
roleBusinessLayer.SaveRole(role);
return RedirectToAction("Index");
}
else
{
return View();
}
}
On View:
<script>
$(document).ready(function () {
$('#SaveRole').click(function () {
var data = $('#RoleForm').serialize();
$.ajax({
type: 'Post',
url: '/Role/Index',
data: data,
success: function (response) {
alert("Role Information Saved!");
}
})
})
})
</script>
what should i do to show the newly entered data on the grid as soon as i click the save button?
I have three partial views on main view
on the first partial view I have search functionality and when user clicks on search I want to refresh results into 3rd partial view.
Controller:
public ActionResult Search()
{
virtualmodel vm = new virtualmodel();
return PartialView(svm);
}
[HttpPost]
public ActionResult Search(ViewModel svm)
{
// Query to retrive the result
// I am not sure what to return from here. Link to another action or just return back to same same partial
}
public ActionResult AnotherPartialPartial()
{
}
In main view
#{Html.RenderAction("Search", "Searchc");
}
How to do it? Do I need ajax?
Using ajax you can call a controller action and return it's response to a particular div.
Empty div:
<div class="row" id="div3">
</div>
Ajax to display html in empty div:
function performSearch(searchCriteria) {
//get information to pass to controller
var searchInformation = JSON.stringify(**your search information**);
$.ajax({
url: '#Url.Action("Search", "ControllerName")',//controller name and action
type: 'POST',
data: { 'svm': searchInformation } //information for search
})
.success(function (result) {
$('#div3').html(result); //write returned partial view to empty div
})
.error(function (xhr, status) {
alert(status);
})
}
jQuery will help you with it!
Try to handle submit button onclick event like this:
$("#yourButtonId").click(function()
{
$.ajax({
type: "POST",
url: "/yourUrl", //in asp.net mvc using ActionResult
data: data,
dataType: 'html',
success: function (result) {
//Your result is here
$("#yourContainerId").html(result);
}
});
});
You can do it with ajax.
First, change your html.beginform to ajax.beginform in your view and add div id into UpdateTargetId that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's "OnSuccess" function. You have to add update function like that:
#using (Ajax.BeginForm("YourAction", "YourController",
new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" }))
{
/*your code*/
}
<script>
function OnSuccessMethod() {
$("#YouWantToChangeSecondDivID").load('/YourController/YourAction2');
$("#YouWantToChangeThirdDivID").load('/YourController/YourAction3');
};
</script>
Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value:
public ActionResult YourControllerName(YourModelType model)
{
...//your code
return PartialView("_YourPartialViewName", YourViewModel);
}
Note: Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
I created a API application where I can perform the crud operations. However, I am unable to display all the models in my cshtml.
I have created my API controller, which has the getAllUsers methods and in my home controller, I just call the Index View. In my view, I have a script which calls the getAllUsers methods. Below is my code:
API controller:
namespace WebApiQues.Controllers
{
public class UserController : ApiController
{
private WebApiQuesEntities db = new WebApiQuesEntities();
//Get all users
public IEnumerable<User> GetAllUsers()
{
var UserList = from s in db.Users
orderby s.Id
select s;
return UserList;
}
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public UserController userController = new UserController();
public ActionResult Index()
{
//var UserList = userController.GetAllUsers();
//ViewBag.UserList = UserList;
return View();
}
}
Index.cshtml:
#{
ViewBag.Title = "Index";
}
#model IEnumerable<WebApiQues.Models.User>
<div>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var uri = 'api/user/getallusers';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (data) {
// Add a list item for the product.
$('<li>').appendTo($('#products'));
});
});
});
</script>
I believe the problem comes from the script in cshtml but I can't find where I am doing it wrong. Any idea?
EDITED:
If I add a console.log(data), I can see that data has the list of users.
try this:
add your jquery script to the scripts section:
#section scripts
{
<script type="text/javascript">
$(function() {
var uri = 'api/user/getallusers';
$.getJSON(uri, function(data) {
$.each(data, function(index, v) {
$('#products').append('<li>'+v.PropertyName+'</li>');
//Change property name to the property of your object
});
});
});
</script>
}
$.each expects two arguments in the callback function: the index of your array and the actual data object itself:
callback Type: Function( Integer indexInArray, Object value ) The
function that will be executed on every object.
http://api.jquery.com/jquery.each/
Assuming User has 'Name' property, try this code
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (data) {
// Add a list item for the product.
$('#products').append('<li>'+data.Name+'</li>');
});
});
I choose from dropdown menu an item and click add => ajax call a method which return JsonResult this is all ok. Then this data should be send to another function PartialViewResult on server side: public PartialViewResult _SkupinaRow(skupinaRow skupinaRow), which generate a new tr with some textbox and labels. My problem is that no binding is made. I get Null when debuggin in _SkupinaRow(skupinaRow skupinaRow)
I have the following domain model defined:
public class skupinaRow
{
public BONUSMALUS bonusmalus { get; set; } //items
public KOLEDAR koledar { get; set; } //calendar
}
Partial View:
#model ObracunPlac.ViewModel.skupinaRow
#Html.HiddenFor(x => x.bonusmalus.bon_id)
.....
Partial view code:
public PartialViewResult _SkupinaRow(skupinaRow skupinaRow)
{
return PartialView("_SkupinaRow", skupinaRow);
}
Ajax Call:
$("#addItemPrihodki").live("click", function () {
var id = $("#prihodkidodaj option:selected").val()
var skupinaRow = {
bonusmalus:{},
koledar:{}
}
jQuery.getJSON("/Placa/getBonusMalus/?id=" + id, function (data) {
console.log("JSON Data: " + data.koledar.kol_id);
skupinaRow.koledar.kol_id = data.koledar.kol_id, //ok
skupinaRow.bonusmalus.bon_id = data.bonusmalus.bon_id, //ok
//alert(JSON.stringify(GetBonusMalusModel($("#bonusdodaj option:selected").val())));
alert(JSON.stringify(data));
// alert(skupinaRow.serialize());
$.ajax({
url: "../_skupinaRow",
cache: false,
data: JSON.stringify(skupinaRow),
//data: JSON.stringify(data),
datatype: JSON,
success: function (html) {
$("#editorRowPrihodki table tr#dodajNov").before(html);
}
,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error'+"+++"+textStatus+"--- "+errorThrown);
},
});
});
return false;
});
public JsonResult getBonusMalus(int id)
{
KOLEDAR koledar = db.KOLEDAR.Single(r => r.kol_id == KoledarID);
BONUSMALUS bm = db.BONUSMALUS.Single(r => r.bon_id == id);
skupinaRow model = new skupinaRow
{
koledar =koledar,
bonusmalus = bm
};
// return Json result using LINQ to SQL
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = model
};
}
Debug picture: https://www.dropbox.com/s/189q080irp0ny77/1.jpg
This worked when i had one model bonusmalus but now I ned two so I created modelView.
How can I bind ViewModel-SkupinaRow to Partial View with strong type SkupinaRow ?
If you are using AJAX only to convert he value to json? then you can use this approach
Set the form with normal post back to Action in controller
use jQuery in your view and on submit of form write this.
$("form").submit(function(){
$("#DropDown_Items").val(JSON.stringify(data));
});
Now you can use this in your Action Method.