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?
Related
This script is supposed to send a ProductId to the home controller's Delete-method, and the controller should make the appropriate Remove-operation:
$('[name="DeleteItem"]').click(function (e) {
$.ajax({
type: "DELETE",
url: "#Url.Action('Delete','Home')",
data: { id: $('DeleteItem#data-id').val() },
success: function () {
alert("success!");
window.location.replace("#Url.Action('Index', 'Home')");
},
error: function (data) {
alert("Error: " + data.id);
}
});
});
This is the form:
<form asp-action="Update">
#foreach (var item in Model.ShoppingCartItems)
{
#item.ProductTitle
<input asp-for="#item.Quantity" />
<button name="DeleteItem" data-id="#item.ProductId">DELETE</button>
}
<button type="submit">Update quantity</button>
</form>
This is the controller's Delete-method (I don't have the ShoppingCartId, so I'm getting it based on SessionId, which is stored in the ShoppingCarts-table):
[HttpDelete]
//[ValidateAntiForgeryToken] // <-- Do I need this in this case?
public async Task<IActionResult> Delete(
[Bind("ShoppingCartItemProductId")]
ViewModelAddToCart model)
{
// Initialize session to enable SessionId
HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
var ShoppingCart = new ShoppingCart()
{
SessionId = SessionId
};
var ShoppingCartItem = new ShoppingCartItem()
{
ProductId = model.ShoppingCartItemProductId,
};
if (ModelState.IsValid)
{
// Find ShoppingCart containing current SessionId.
var cartInfo =
(from Cart in _context.ShoppingCarts
where Cart.SessionId == SessionId
select new { TempId = Cart.Id })
.SingleOrDefault();
if (cartInfo != null)
{
ShoppingCartItem.ShoppingCartId = cartInfo.TempId;
}
// Find ShoppingCartItem containing current ProductId:
var cartItemInfo =
(from CartItem in _context.ShoppingCartItems
where (CartItem.ShoppingCartId == ShoppingCartItem.ShoppingCartId &&
CartItem.ProductId == model.ShoppingCartItemProductId)
select new { TempId = CartItem.Id })
.FirstOrDefault();
if (cartItemInfo != null)
{
// Delete ShoppingCartItem
ShoppingCartItem.Id = cartItemInfo.TempId;
_context.ShoppingCartItems.Remove(ShoppingCartItem);
}
await _context.SaveChangesAsync();
return RedirectToAction("Index", "Home");
}
else
{
return View("Index", "Home");
}
}
Edit I have made some changes to my code, and now I receive "Error: undefined" in an alert. That is because the error: in the ajax is triggered, and the data-object is not defined. Why is that? And a second question is what is the controller supposed to return? As I understand, not a RedirectToAction.
what is "deleteitem"
you should have some id or class for the button in your case class should be easy
<button name="DeleteItem" class = "deleteitemevent" data-id="#item.ProductId">DELETE</button>
$(".deleteitemevent").click(function (e) {
}
[HttpPost]
[ValidateAntiForgeryToken]
//^^yes you should for any post... but since you insist on
//doing ajax calls...
//you will have to research how to build this up... from JS and inject with the ajax call..
public async Task<IActionResult> Delete(
[Bind("ShoppingCartItemProductId")]
ViewModelAddToCart model)
{
//...
}
$('[name="DeleteItem"]').click(function (e) {
var dataid = $(this).attr('data-id'); // because name was used for control not id
$.ajax({
type: "POST",
url: "#Url.Action('Delete','Home')",
data: { id: dataid },
success: function () {
alert("success!");
window.location.replace("#Url.Action('Index', 'Home')");
},
error: function (data) {
alert("Error: " + data.id);
}
});
});
I think you have a long way to go... There are easier ways of doing this without needing ajax calls...
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
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 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.
I have this string variable call "status" which is updated by a serial port connection I've made. the "status" show's if u are connected to the serial port or not.
I've made a simple 2 buttons view. one opens the connection and the other close it.
i want to be able to auto update the status of the connection inside the view.
i guess i need to use some kind of timer which shows the string inside "status" every given time, but i have no clue on how to do it..
This is my HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult CheckStatus()
{
return Json(new { status = "active" });
}
}
and this is my view:
<script type="text/javascript">
$(function() {
// poll every 5 seconds
setInterval('checkStatus()', 5000);
}
function checkStatus() {
$.ajax({
url: 'Home/CheckStatus',
type: 'POST',
dataType: 'json',
success: function(xhr_data) {
if(xhr_data.status == 'active') {
// this would just disable the "Open" button
$('#btnOpen').attr('disabled', 'disabled');
}
}
});
}
I'm going to assume you can use jQuery, and that you have a Controller action that looks like this:
[HttpPost]
public class StatusController : Controller
{
public JsonResult CheckStatus()
{
return Json(new { status = "active" });
}
}
Then, in your view add the following script
<script type="text/javascript">
$(function() {
// poll every 5 seconds
setInterval('checkStatus()', 5000);
}
function checkStatus() {
$.ajax({
url: 'Status/CheckStatus',
type: 'POST',
dataType: 'json',
success: function(xhr_data) {
if(xhr_data.status == 'active') {
// this would just disable the "Open" button
$('#btnOpen').attr('disabled', 'disabled');
}
}
});
}
</script>