Answer the question
In order to leave comments, you need to log in
ASP NET MVC 5. How to update a partial view?
Hello! I'm trying to write an application. There is a balance and 3 buttons: 1, 2, 5 coins. The page displays the current balance. When you click on one of the coin buttons, the balance should increase and the partial page view should update accordingly. Please help with advice.
Model:
namespace DrinkApp.Models
{
public class Payer
{
public int balance { get; set; }
public int[] coins = {1, 2, 5};
public Payer()
{
balance = 50;
}
}
}
<table>
<tr class="header">
<td><p>Название напитка</p></td>
<td><p>Описание</p></td>
<td><p>Остаток</p></td>
<td><p>Цена</p></td>
<td></td>
</tr>
@foreach (var d in ViewBag.Drinks)
{
<tr>
<td><p>@d.Name</p></td>
<td><p>@d.Description</p></td>
<td><p>@d.Amount</p></td>
<td><p>@d.Price</p></td>
<td><div class="col-md-offset-2 col-md-10"><input type="submit" value="Купить" class="btn btn-default" /></div> </td>
</tr>
}
</table>
<div id="partialDiv">
@{Html.RenderPartial("Partial");}
</div>
@for (int i = 0; i < Model.coins.Length; i++)
{
@*<div class="text"><input type="submit" value= @Model.coins[i] class="btn btn-default" /></div>*@
<div class="text"> @Ajax.ActionLink("Нажми ", "AddCoin", "Home", new { coin = Model.coins[i] }, new AjaxOptions() { UpdateTargetId = "partialDiv" }, null)</div>;
}
</div>;
<style>
.text {
text-align: center;
}
</style>
@model DrinkApp.Models.Payer
<h2>@ViewBag.Message</h2>
<div class="text">
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
Ваш баланс: @Model.balance</div>
public class HomeController : Controller
{
// создаем контекст данных
DrinkContext context = new DrinkContext();
Payer payer = new Payer();
// GET: Home
public ActionResult Index()
{
//Получаем из бд объекты Drink
IEnumerable<Drink> drinks = context.Drinks;
// передаем все объекты в динамическое свойство Drinks и Payer в ViewBag
ViewBag.Message = "Это вызов частичного представления из обычного";
ViewBag.Drinks = drinks;
return View(payer);
}
//public PartialViewResult Partial(int coin = 0)
//{
// ViewBag.Message = "Это частичное представление.";
// payer.balance += coin;
// return PartialView(payer);
//}
public PartialViewResult AddCoin(int coin = 0)
{
ViewBag.Message = "Это частичное представление.";
payer.balance += coin;
return PartialView("Partial", payer);
}
//закрытие подключения
protected override void Dispose(bool disposing)
{
context.Dispose();
base.Dispose(disposing);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question