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
Related
I created a repository and now i want to use a foreach to add multiple items to the page but its giving me a error. My objective is: when there is no items in the page it will show a message but if the page have items will show a different message and the items. The code is the following:
Controller:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Treino1.Models;
namespace Treino1.Controllers
{
public class DespesasController : Controller
{
public IActionResult Index()
{
List<Despesa> despesas = RepositorioDespesas.Despesas;
return View(despesas);
}
[HttpGet]
public IActionResult NovaDespesa()
{
return View();
}
[HttpPost]
public IActionResult NovaDespesa(Despesa despesa)
{
if (ModelState.IsValid)
{
RepositorioDespesas.AddDespesa(despesa);
return View("DespesaConfirmada", despesa);
}
return View();
}
}
}
Repository
using System.Collections.Generic;
namespace Treino1.Models
{
public static class RepositorioDespesas
{
private static List<Despesa> despesas = new List<Despesa>();
public static List<Despesa> Despesas
{
get { return despesas; }
}
public static void AddDespesa (Despesa newDespesa)
{
despesas.Add (newDespesa);
}
}
}
#{
ViewData["Title"] = "Despesa Confirmada";
}
#model List<Treino1.Models.Despesa>
#if (Model.Count== 0)
{
<h1>Sem Despesas...</h1>
}
else
{
<h1>Despesas!</h1>
#foreach (Treino1.Models.Despesa d in Model)
{
<div class="card bg-secondary border-dark">
<div class="card-body">
<b>Nome da Despesa: </b> #d.NomeDespesa
<b>Quantidade: </b> #d.Quantidade
<b>Valor: </b> #d.Valor
<b>Categoria: </b> #d.Categoria
<b>Pago? </b>
#if (d.Pago)
{
#:Sim
}else
{
#:Não
}
</div>
</div>
}
}
<div>
<a asp-action="NovaDespesa">Nova Despesa</a>
</div>
I think the error is something about the Model.Count==0 but i dont know how to solve.
The error is this:
The data model in the DespesaConfirmada strongly typed view is defined as #model List<Treino1.Models.Despesa>, but when it rendered from the public IActionResult NovaDespesa(Despesa despesa) action method the single Treino1.Models.Despesa object is passed. Try to use like below:
public IActionResult NovaDespesa(Despesa despesa)
{
if (ModelState.IsValid)
{
RepositorioDespesas.AddDespesa(despesa);
// Obtain corresponded records from the repository and pass to the view.
return View("DespesaConfirmada", RepositorioDespesas.Despesas());
}
return View();
}
Using Core 3.1 and Razor Pages
I trying to undertake the simple task of passing a search string into a ViewComponent and invoke the results.
I have encountered two issue I cannot find help with:
How to pass the input search string to the view component?
How to invoke the view component when the search button is clicked?
_Layout Page
<input id="txt" type="text" />
<button type="submit">Search</button>
#await Component.InvokeAsync("Search", new { search = "" })
//Should equal input string
I am new to core so any nudges in the right direction would be appreciated.
View component is populated on server side and then return to your client for rendering, so you can't directly pass client side input value into view component . In your scenario , when clicking search button , you can use Ajax to call server side method to load the view component and pass the input value :
Index.cshtml
<input id="txt" type="text" />
<button onclick="loadcomponents()">Search</button>
<div id="viewcomponent"></div>
#section Scripts{
<script>
function loadcomponents() {
$.ajax({
url: '/?handler=Filter',
data: {
id: $("#txt").val()
}
})
.done(function (result) {
$("#viewcomponent").html(result);
});
}
</script>
}
Index.cshtml.cs
public IActionResult OnGetFilter(string id)
{
return ViewComponent("Users", new { id = id });
}
UsersViewComponent.cs
public class UsersViewComponent : ViewComponent
{
private IUserService _userService;
public UsersViewComponent(IUserService userService)
{
_userService = userService;
}
public async Task<IViewComponentResult> InvokeAsync(string id)
{
var users = await _userService.GetUsersAsync();
return View(users);
}
}
Edit: Oh, you edited the razor tag in after I posted my answer. Well, my answer is only valid for ASP.NET Core MVC.
I assume that your controller looks something like this:
[HttpGet]
public IActionResult Index()
{
var model = new IndexVM();
return View(model);
}
[HttpPost]
public IActionResult Index(IndexVM model)
{
// you can do something with the parameters from the models here, or some other stuff
return View(model);
}
Your ViewModel can look like this:
public class IndexVM
{
public string SearchTerm {get;set;}
}
Your View where you use your ViewComponent:
#model IndexVM
// <form tag ...
<input asp-for="SearchTerm" />
<button type="submit">Search</button>
#await Component.InvokeAsync(nameof(Search), Model)
ViewComponent:
public class Search : ViewComponent
{
public IViewComponentResult Invoke(IndexVM indexVM)
{
// Do something with indexVM.SearchTerm
}
}
View of ViewComponent:
#model IndexVM
// ...
I am wondering how can I count the number of times a button in my view was clicked using sessions and not using jQuery, just asp.net.
Here is my action method (empty) :
public ActionResult ClickCounter()
{
return View();
}
and my view :
#{
ViewBag.Title = "ClickCounter";
}
<h2>ClickCounter</h2>
#using (#Html.BeginForm())
{
<!-- form content here -->
#Session["num"] = 0;
<form method="post">
<fieldset>
<legend>Button clicks counter</legend>
<div>
<label for="Clciks">Clicks:</label>
<h2>#Session["num"]</h2>
</div>
<div>
<label> </label>
<input type="submit" value="Click!" class="submit" />
</div>
</fieldset>
</form>
}
Excuse me for the lame questions, but I am a complete novice and trying to understand how this stuff work. I tried googleing.
I just want to display the click count in the h2 in my view using sessions for the purpose.
Any tips will be appreciated.
If it is for simply increasing the clicked count on form submit, You can update your http post action method to read the session value if exist and increase and set it back. If not exist, initialize it.
const string sessionVariableName = "num";
public ActionResult ClickCounter()
{
if (Session[sessionVariableName] == null)
{
Session[sessionVariableName] = 0;
}
return View();
}
[HttpPost]
public ActionResult ClickCounter(string dummyParam)
{
if (Session[sessionVariableName] == null) // should not happen!
{
Session[sessionVariableName] = 0;
}
else
{
var n = (int)Session[sessionVariableName];
n++;
Session[sessionVariableName] = n;
}
return View();
}
Make sure that you are doing a GET form method on submit.
You also need to remove the (re) initialization in the view this line #Session["num"] = 0; as we are doing that in the action method. Also you should not have nested forms as it is invalid. Html.BeginForm helper will render the markup for the form tag. So remove the inner form tag you have.
You have tagged this question as asp.net-mvc, why not take advantage of the framework?
Model
class MyModel
{
public int ClickCount { get; set; }
}
View
#model MyModel
#{
ViewBag.Title = "ClickCounter";
}
<h2>#ViewBag.Title</h2>
<form method="post">
<!-- hidden input of the current click count -->
#Html.HiddenFor(m => m.ClickCount)
<fieldset>
<legend>Button clicks counter</legend>
<div>
#Html.LabelFor(m => m.ClickCount)
<h2>#Model.ClickCount</h2>
</div>
<div>
<button type="submit">Submit!</button>
</div>
</fieldset>
</form>
Controller
const string clickCountSessionKey = "clickCount";
[HttpGet]
public ActionResult ClickCounter()
{
// initialize the model
var model = new MyModel() { ClickCount = 0 };
var previousClickCount = Session[clickCountSessionKey];
if (previousClickCount != null)
{
model.ClickCount = (int)previousClickCount;
}
return View(model);
}
[HttpPost]
public ActionResult ClickCounter(MyModel model)
{
// increment the click count of the model
model.ClickCount++;
// track the click count in the session
Session[clickCountSessionKey] = model.ClickCount;
return View(model);
}
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);
}
});
});
});
I have got the two buttons in the same view one is working with the data to show in a label in another view and I have written the function for the button2 (adding another value), when I click on the button2 its not showing the data in view ..... rather it's giving error like this ... http:404 Resource not found error
and this is the view
#model MvcSampleApplication.Models.products
#{
ViewBag.Title = "Valuesadd";
}
<h2>Valuesadd</h2>
#using (Html.BeginForm("SubmitValue","EnterValue",FormMethod.Post))
{
<div>
<fieldset>
<legend>Enter Textbox Value</legend>
<div class ="editor-label">
#Html.LabelFor(m => m.EnteredValue)
</div>
<div class="editor-field">
#Html.TextBoxFor(m=>m.EnteredValue)
</div>
<p>
<input type="submit" value="Submit1" />
</p>
</fieldset>
</div>
}
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
<p>
<input type="submit" value="Submit2" />
</p>
}
and this is the controller for
namespace MvcSampleApplication.Controllers
{
public class EnterValueController : Controller
{
[HttpPost]
public ActionResult SubmitValue(MvcSampleApplication.Models.products model)
{
TempData["logindata"] = model.EnteredValue;
return RedirectToAction("submittedvalues" , "SubmitValue2");
// how can we redirect to another view when the button is clicked in one view
}
public ActionResult submittedvalues()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = data;
return View(model);
}
// action for second button click
public ActionResult submittedvalues2()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = "HIIII"+data;
return View(model);
}
}
}
would you pls suggest any idea ..
Many thanks...
Your form action and action in the controller are not named the same. Also you don't have a HttpPostfor it
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
}
//add this
[HttpPost]
public ActionResult submittedvalues2()
{
var model = SOMETHING;
return View("submittedvalues", model);
}
or
[HttpPost]
public ActionResult submittedvalues2()
{
//Do your post actions and redirect to action
return RedirectToAction("submittedvalues");
}
SubmitValue2 in the form should be submittedvalues2, and add a HttpPost attribute on it