I have a simple controller and view:
I just want the Index.cshtml view page to be reloaded with new data.I have debugged the code thoroughly. Infact, clicking on the "ul" when the control goes to the Index(string value) method the model object is populated with new data and even in the cshtml page the Model is showing the new list in the debugger, but the view is NOT getting refreshed. I really don't know why.. Can anyone help me plz?
If I have gone wrong horribly somewhere please excuse my ignorance as I am new to MVC.
Thanks in advance...
Controller:
namespace MVCTestApp1.Controllers
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
ModelState.Clear();
List<string> ll = new List<string>();
ll.Add("qq");
ll.Add("aa");
ll.Add("zz");
return View(ll);
}
[HttpPost]
public ActionResult Index(string value)
{
ModelState.Clear();
List<string> ll = new List<string>();
ll.Add("kkk");
ll.Add("qq");
ll.Add("aa");
ll.Add("zz");
return View(ll);
}
}
}
View:
#model IEnumerable<string>
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<h2>Index</h2>
<ul id="bb">
#foreach (var i in Model)
{
<li>#Html.DisplayFor(ir=>i)</li>
}
</ul>
}
I suppose that you wrote some javascript code so that when the user clicks on a <li> element of the <ul> you are triggering an AJAX call to the [HttpPost] action sending the selected value to the server. The problem with your code might be that you probably forgot to update the DOM with the new contents in your success callback. So for this to work you could start by placing the <ul> contents in a partial view:
List.cshtml:
#model IEnumerable<string>
#foreach (var i in Model)
{
<li>#Html.DisplayFor(ir=>i)</li>
}
and then include this partial in the main view:
#model IEnumerable<string>
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<h2>Index</h2>
<ul id="bb">
#Html.Partial("_List", Model)
</ul>
}
OK, now in your POST action you could return the partial:
[HttpPost]
public ActionResult Index(string value)
{
List<string> ll = new List<string>();
ll.Add("kkk");
ll.Add("qq");
ll.Add("aa");
ll.Add("zz");
return PartialView("_List", ll);
}
and the final bit is the javascript code:
$(function() {
$('#bb').on('click', 'li', function() {
var value = $(this).html();
$.ajax({
url: $(this).closest('form').attr('action'),
type: 'POST',
data: { value: value },
success: function(partialView) {
$('#bb').html(partialView);
}
});
});
});
Related
I want to load mvc grid with data from controller:
Code:
GridView dumasGrid:
#model IEnumerable<BoneID.Dumas.Obroci>
#{
ViewBag.Title = "PopisObroka";
WebGrid grid = new WebGrid(Model, ajaxUpdateContainerId: "tblGrid");
}
<div>
#grid.GetHtml();
</div>
View page that load grid view page: dumasGridPlaner:
#using BoneID.Classes
#using BoneID.Net.Static
#model BoneID.Web.Models.ModelDefault
#{
var isIzoProd = Model.ParametriEx.Any(a => a.Type == CParametriEx.ParametriExType.IzoProd);
}
<div>
#Html.Partial("dumasGrid");
</div>
Main page that load page with grid: Dumas
<div id="tabs-1">
#Html.Partial("dumasGridPlaner",Model.Default)
</div>
My controller:
namespace BoneID.Web.Client.Controllers
{
public class DumasController : Controller
{
public ActionResult Index()
{
return View();
}
[ChildActionOnly]
public ActionResult PopisObroka()
{
Obroci obr = new Obroci();
var menu = obr.GetObroci();
return PartialView(menu);
}
}
}
Error that I get on page DumasGridPlaner:
System.InvalidOperationException: 'The model item passed into the dictionary is of type 'BoneID.Web.Models.ModelDefault', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[BoneID.Dumas.Obroci]'
What is the problem? What am I calling wrong?
I'm using this class :
public class SteamGet
{
public delegate ActionResult ResultDone(List<Steam> List);
public event ResultDone OnResultDone;
public void Get()
{
Debug.Write("Result Received !");
using (WebClient client = new WebClient())
{
string data = client.DownloadString("http://api.steampowered.com/ISteamApps/GetAppList/v0001/");
JObject steamobject = JObject.Parse(data);
var rslt = steamobject.SelectToken("applist").SelectToken("apps");
var objd = JsonConvert.DeserializeObject<ObjectResult>(rslt.ToString());
OnResultDone(objd.MyList);
}
}
}
And my home controller looks like this :
public class HomeController : Controller
{
// GET: Home
protected SteamGet Getter = new SteamGet();
public ActionResult Index()
{
Getter.OnResultDone += Getter_OnResultDone;
Task.Run(() => Getter.Get());
return View();
}
private ActionResult Getter_OnResultDone(List<Models.Steam> List)
{
return View("ViewTest",List);
}
}
so as you can see i'm calling the Get() Method then Returning the View , when the Event OnresultDone Raised i want to Call another View or refreshing the home view
my home view :
#using TemplateAspTest.Repository
#model List<TemplateAspTest.Models.Steam>
#{
ViewBag.Title = "Home";
Layout = "~/Views/Shared/_Main.cshtml";
}
<section id="intro" class="main">
<span class="icon fa-diamond major"></span>
<h2>Test one section ! </h2>
<p>
test done !
</p>
<ul class="actions">
#{
if (#Model == null)
{
<li>waiting ....</li>
}
else
{
<li>ViewBag.Message;</li>
#Model[0].Name;
}
}
</ul>
</section>
EDIT :
i'am Returning View and waiting for a event to be raised i want to call another view when the even is raised
I expect to receive the value of the button to a.aaa
but i get null instead
a.aaa needs to be "stackOverflow" string in [HttpPost]
controller code
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Class1 a)
{
return View();
}
}
model
namespace WebApplication3.Models
{
public class Class1
{
public string aaa { get; set; }
}
}
view
#model WebApplication3.Models.Class1
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<button type="button" name="aaa" id="aaa" value="stackOverflow">pressMe</button>
<input type="submit" />
}
This works correctly for me. Set a breakpoint at the return View(); line in the ActionResult Index(Class1 a) method.
This should demonstrate that a contains a value of stackOverflow for it's property aaa.
If you cannot replicate this behavior, please clarify the behavior that you would expect.
What is [HttpPost] ?
You should find the value in Request["aaa"]
#using (Html.BeginForm("Index", "DefaultController ", FormMethod.Post))
{
<p>
#Html.TextBox("aaa", "stackOverflow")
<input type="submit" value="Text" />
</p>
}
This code should work for sure, you can try it !
I recommend implementing via javascript/ajax
In your html's body
Press Me
In your html's script
function myJsFunc(somedata) {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/DefaultController/Index',
data: { 'somedata' : somedata },
success: function(result) {
//do something
}
error: function (errorData) {alert(errorData);}
});
};
In your controller
[HttpPost]
public ActionResult Index(string somedata)
{
if(somedata == "aaa")
{
//do something
}
return Json("successData");
}
Then style links as buttons with css.
Or replace your buttons with inputs and follow these examples
I am doing a web application using ASP.NET MVC 5. It seems to me that I did everything as it goes, but ajax is just not working. I see results only after refreshing.
This is in my View:
#{
AjaxOptions ajaxOptions = new AjaxOptions {
UpdateTargetId = "CommmentList",
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace};
}
<div id="CommentList">
#using (Ajax.BeginForm("Index", "Comment", ajaxOptions))
{
// some content
<div>
#Html.Action("_AddCommentForItem", "Comment")
</div>
}
</div>
This is in a layout view:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
EDIT:
These are actions in a Comment controller:
// GET: Comment
public async Task<ActionResult> Index()
{
var comments = db.Comments.Include(k => k.Item);
return View(await comments.ToListAsync());
}
// GET
public PartialViewResult _AddCommentForItem()
{
ViewBag.ItemId = new SelectList(db.Items, "Id", "Name");
return PartialView("_AddCommentForItem");
}
// POST
[HttpPost]
public PartialViewResult _AddCommentForItem ([Bind(Include = "Id,ItemId,CommentContent")] Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.Add(commment);
db.SaveChanges();
}
ViewBag.ItemId = new SelectList(db.Items, "Id", "Name", comment.ItemId);
return PartialView("_AddCommentForItem");
}
}
}
I included partial view _AddCommentForItem, which is creating a comment, in an index view of the Comment controller. That's way i want the result to be visible right away, without refreshing.
What am I missing?
Thank you.
I'm developing an mvc 4 application and I'm just about done. I have two controllers are there.
public ActionResult Index()
{
return View(new Resources());
}
public ActionResult ResourceDetails(int id = 1)
{
ResourceItems re = new Resources().GetResDetails(id);
return View(re);
}
ResourceDetails is a partial viewpage .it contains
#model ....Models.ResourceItems
<div>
#Html.Raw(#Model.Res_Details)
</div>
and index page contains
#model IEnumerable<.....Models.ResourceItems>
<ul id="res">
#foreach(var Item in Model)
{
<a href="~/Resources/ResourceDetails/#Item.Id" ><li>#Item.Res_NA</li></a>
}
</ul>
<div id="rescontent">
</div>
I want load the partial page in to the div "rescontent" based on Id. Defaultly Id is 1. how it possible
You could use AJAX:
#model IEnumerable<Puthencruz.Rotary.Club.Models.ResourceItems>
<ul id="res">
#foreach(var item in Model)
{
<li>
#Html.ActionLink(
item.Res_NA,
"ResourceDetails",
"Resources",
new { id = item.Id },
new { #class = "detail" }
)
</li>
}
</ul>
<div id="rescontent">
</div>
and then in a separate javascript file you could use jQuery to subscribe to the .click event of the anchors and send an AJAX request to the Details controller action sending the current item id and then render the results in the #rescontent div:
$(function() {
$('.detail').click(function() {
$('#rescontent').load(this.href);
return false;
});
});
Also from your controller action make sure you are returning a partial view:
public ActionResult ResourceDetails(int id = 1)
{
ResourceItems re = new Resources().GetResDetails(id);
return PartialView(re);
}