View not updating when model changed - asp.net-core-mvc

I have a single page UI, which looks like below .
on the UI there are two checkboxes, when user toggle the states of checkbox, I use ajax to post the status to HomeController in a POST action.
after updated the model in POST action with the new checkboxes states, I redirect back to GET action to return a view.
however, the UI does not refresh with the new model.
can someone help on this ? thanks.
Views/Home/Index.cshtml
#{
Layout = "_Layout";
}
#model WebApplication5.Controllers.HomeModel;
<h1>STS</h1>
<div>
<input type="checkbox" id="UseVersionCheckBox" />Use version v1 in url
</div>
<br />
<div>
<input type="checkbox" id="ResponseTypeTokenCheckBox" /> Return access token in url
</div>
<div>your check status : #Model.IsChecked</div>
<br />
<div>your text : #Model.Text </div>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - WebApplication5</title>
</head>
<body>
#RenderBody()
<script src="~/jquery-2.1.0.min.js"></script>
#RenderSection("Scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
function fun() {
var current = $("#UseVersionCheckBox").prop("checked");
var current2 = $("#ResponseTypeTokenCheckBox").prop("checked");
alert("values as:" + current + "," + current2);
var json = {};
json.UseVersionChecked = current;
json.ResponseTypeTokenChecked = current2;
var text = JSON.stringify(json);
$.ajax({
type: "POST",
url: "Home/Index",
data: text,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (r, s, e) {
},
success: function (r) {
},
complete: function () {
}
});
}
$("#UseVersionCheckBox").click(fun);
$("#ResponseTypeTokenCheckBox").click(fun);
});
</script>
</body>
</html>
HomeController.cs
public class HomeController : Controller
{
public HomeController()
{
}
public IActionResult Index()
{
HomeModel model;
if (TempData.ContainsKey("model"))
{
var newmodel = JsonConvert.DeserializeObject<HomeModel>(TempData["model"].ToString());
model = newmodel;
}
else
{
model = new HomeModel();
model.IsChecked = false;
model.Text = "not checked";
}
ModelState.Clear();
return View(model);
}
[HttpPost]
public IActionResult Index([FromBody] CheckStatus status)
{
HomeModel model = new HomeModel();
model.IsChecked = true;
model.Text = "UseVersionCheckBox : " + status.UseVersionChecked + " ; ResponseTypeTokenCheckbox : " + status.ResponseTypeTokenChecked;
if (TempData.ContainsKey("model"))
TempData.Remove("model");
TempData.Add("model", JsonConvert.SerializeObject(model));
ModelState.Clear();
return RedirectToAction("Index", "Home");
}
}
[Serializable]
public class HomeModel
{
public bool IsChecked { get; set; }
public string Text { get; set; }
}
public class CheckStatus
{
public bool UseVersionChecked { get; set; }
public bool ResponseTypeTokenChecked { get; set; }
}
weird thing , after checked the response of redirect to GET action, the new value is there ,but web page in browser still show old. why ?

Related

How can i send a list of an object to my controller?

I try to send a list of object to controller but controller always receives it as null.
var model= #Html.Raw(Json.Encode(Model.MultipleElements));
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: '#Url.Action("AddField", "Flux")',
data: model,
success: function (response) {
$(".destinationMultiple").html(response);
}
});
And here is my controller action
public PartialViewResult AddField(List<Destination> model)
{
return PartialView("_myPartialView");
}
You can use Ajax.Beginform. If you want you can do the following, which explains how to pass arrays from View to Controller.
View/Controller
namespace Testy20161006.Controllers
{
public class Destination
{
public string aDestination { get; set; }
}
public class TahtohViewModel
{
public List<Destination> MultipleElements { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult AddField(List<Destination> MultipleElements)
{
List<String> sendout = new List<string>();
foreach (Destination dest in MultipleElements)
{
sendout.Add(dest.aDestination);
}
ViewBag.SendoutList = sendout;
return PartialView("_myPartialView");
}
public ActionResult Tut149()
{
Destination dest1 = new Destination { aDestination = "adest1" };
Destination dest2 = new Destination { aDestination = "adest2" };
Destination dest3 = new Destination { aDestination = "adest3" };
TahtohViewModel tahtoViewModel = new TahtohViewModel { MultipleElements = new List<Destination>() };
tahtoViewModel.MultipleElements.Add(dest1);
tahtoViewModel.MultipleElements.Add(dest2);
tahtoViewModel.MultipleElements.Add(dest3);
return View(tahtoViewModel);
}
View
#model Testy20161006.Controllers.TahtohViewModel
#using Testy20161006.Controllers
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut149</title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var items = [];
var q = $("input[name='theElemsName']");
$.each(q, function (index, thevalue) {
var item = {};
item.aDestination = thevalue.value;
items.push(item);
});
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("AddField", "Home")',
data: JSON.stringify(items),
success: function (response) {
//alert("success");
$(".destinationMultiple").html(response);
}
});
})
})
</script>
</head>
<body>
<div>
<table>
#{ var index = 0;}
#foreach (Destination item in Model.MultipleElements)
{
<tr><td>Item <span>#(index++)</span></td><td data-multipleelements="#(index)">#Html.TextBox(item.aDestination, null, new { Name = "theElemsName", Value = item.aDestination })</td></tr>
}
</table>
<input type="button" id="theButton" value="Add Field" />
<div class="destinationMultiple"></div>
</div>
</body>
</html>
Partial View
my partial view
#foreach (string item in ViewBag.SendoutList)
{
<div>#item</div>
}

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>

Ajax WebGrid Paging MVC3

I'm using WebGrid and I need to switch between pages with Ajax.
Index Code
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
#using (Ajax.BeginForm("GetGrid", new AjaxOptions() { UpdateTargetId = "Res" }))
{
<input type="text" />
<input type="submit" value="start" />
<div id="Res">
</div>
}
Result partial view
#model IEnumerable<MvcApplication1.Controllers.Model>
<div id="grid2">
#{
var grid = new WebGrid(source:Model,rowsPerPage:6,ajaxUpdateContainerId: "grid2");
#grid.GetHtml(htmlAttributes: new { id = "grid2" },
columns: grid.Columns(
grid.Column("Someting")
));
}
</div>
Controller Code
public class ABCController : Controller
{
//
// GET: /ABC/
public ActionResult Index()
{
return View();
}
public static List<Model> mo = new List<Model>();
[HttpPost]
public ActionResult GetGrid()
{
for (int i = 0; i < 1000; i++)
{
mo.Add(new Model() { Someting = i.ToString() });
}
return PartialView("Result", mo);
}
}
public class Model
{
public string Someting { get; set; }
}
This work for first page but nothing happens for other pages.
After some hours i could not find some thing that help me.i noticed to html code of my page links.
page link
2
so i finally got how it's work.i add an ActioResult to my controller like this:
[HttpGet]
public ActionResult GetGrid(int page)
{
return PartialView("Result",mo);
}
and worked.i hope this be helpfull for some one

How to Show The image from one view to other view in Asp.Net WebApi MVC4?

HI all i have some images which i am retrieving dynamically and displaying in a view like this
here is my controller
private ProductEntities products = new ProductEntities();
public List<ProductItems> GetAllProducts()
{
var items = new List<ProductItems>();
var records = products.Products.ToList();
foreach (var item in records)
{
ProductItems model = new ProductItems();
model.ProductID = item.ProductId;
model.ProductName = item.ProductName;
model.ImageURL = item.ImageURL;
items.Add(model);
}
return items;
}
and this is my index page view
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductDetails", function (data) {
$.each(data, function (idx, ele) {
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
$("#makeMeScrollable").append('<h4>' + ele.ProductName + '</h4>');
});
});
});
</script>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
</body>
now what i want is when ever an user clicks on a image i have to pass the ID of the image to my method in my apicontroller and i have to display that image in another view ..how do i pass my image to another view and Id to my api/controller action
i have to pass my ProductID to this method
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
return productdeatils ;
}
The thing is that API actions do not return views. They are used to serialize models using some format such as JSON or XML. So when you are saying that you want to use the ProductDeatils API action to display a view, this doesn't make much sense. Views are returned by standard ASP.NET MVC controller actions returning ActionResults. So let's see how to set this up.
Let's suppose that you have the following API controllers:
public class ProductsController : ApiController
{
private ProductEntities products = new ProductEntities();
public IEnumerable<ProductItems> Get()
{
return products.Products.ToList().Select(item => new ProductItems
{
ProductID = item.ProductId,
ProductName = item.ProductName,
ImageURL = item.ImageURL
});
}
}
public class ProductDetailsController : ApiController
{
private ProductEntities products = new ProductEntities();
public ProductItems Get(long id)
{
return products.ExecuteStoreQuery<ProductItems>(
"GetProductDetail #ProductID ",
new SqlParameter("#ProductID", id)
);
}
}
Alright, now we will need standard ASP.NET MVC controller that will serve the views:
public class HomeController : Controller
{
public ActionResult Products()
{
return View();
}
public ActionResult ProductDetail(long id)
{
using (var client = new HttpClient())
{
var productDetailUrl = Url.RouteUrl(
"DefaultApi",
new { httproute = "", controller = "productdetails", id = id },
Request.Url.Scheme
);
var model = client
.GetAsync(productDetailUrl)
.Result
.Content
.ReadAsAsync<ProductItems>()
.Result;
return View(model);
}
}
}
and the respective view for showing the list of products and the detail of a product when a link is clicked:
~/Views/Home/Products.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
<script type="text/javascript" src="~/scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
var productsUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
var productDetailUrl = '#Url.Action("productdetail", "home", new { id = "__id__" })';
$.getJSON(productsUrl, function (data) {
$.each(data, function (idx, product) {
$('<img/>').attr({ src: product.ImageURL }).appendTo('#makeMeScrollable');
$('#makeMeScrollable').append(
$('<h4/>').html(
$('<a/>', {
href: productDetailUrl.replace('__id__', product.ProductID),
text: product.ProductName
})
)
);
});
});
</script>
</body>
</html>
and ~/Views/Home/ProductDetail.cshtml:
#model ProductItems
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ProductDetail</title>
</head>
<body>
<h4>#Html.DisplayFor(x => x.ProductName)</h4>
<img src="#Model.ImageURL">
</body>
</html>

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