ı am using a view in ajax begin form. ı search one thing and result is correct then alert not render the partial view. but it isnt render correct view a blank page and a see my partial view. thanks
my view
#using (Ajax.BeginForm("AjazKullanici", new AjaxOptions { UpdateTargetId = "trBilgiler", HttpMethod = "Post" }))
{
<tr>
<td style="width: 20%">
T.C. Kimlik No :
</td>
<th align="left">
#Html.TextBoxFor(model => model.TcNo)
#Html.ValidationMessageFor(model => model.TcNo)
<input type="submit" id="btnBilgiGetir" value="Bilgi Getir" class="Button" width="75px" />
</th>
</tr>
}
<tr id="trBilgiler">
#{Html.RenderPartial("BilgilerKullanici");}
</tr>
my controller
public ActionResult AjazKullanici()
{
ViewData["dropGizliSoru"] = _db.EHASTANEGIZLISORUs;
return View();
}
[HttpPost]
public PartialViewResult AjazKullanici(YeniKullaniciModel model)
{
if (model.TcNo != null)
{
var userKontrol = _db.KULLANICIBILGILERIs.Where(x => x.KULLANICIKOD == model.TcNo);
if (userKontrol.Any())
{
Response.Write("<script langauge='javascript'>alert('Girmiş Olduğunuz T.C. Kimlik Numarasına Ait Kullanıcı Kaydı Vardır.')</script>");
return PartialView();
}
else
{
return PartialView("BilgilerKullanici",model);
}
}
return PartialView();
}
Related
I read the book 'Pro Entity Framework Core 2 for ASP.NET MVC'. I'm currently at the beginning of chapter 12 and have some problems. I have this controller:
namespace DataApp.Controllers
{
public class HomeController : Controller
{
private IDataRepository repository;
public HomeController(IDataRepository repo)
{
repository = repo;
}
public IActionResult Index()
{
return View(repository.GetAllProducts());
}
public IActionResult Create()
{
ViewBag.CreateMode = true;
return View("Editor", new Product());
}
[HttpPost]
public IActionResult Create(Product product)
{
repository.CreateProduct(product);
return RedirectToAction(nameof(Index));
}
public IActionResult Edit(long id)
{
ViewBag.CreateMode = false;
return View("Editor", repository.GetProduct(id));
}
[HttpPost]
public IActionResult Edit(Product product)
{
repository.UpdateProduct(product);
return RedirectToAction(nameof(Index));
}
[HttpPost]
public IActionResult Delete(long id)
{
repository.DeleteProduct(id);
return RedirectToAction(nameof(Index));
}
}
}
The index view looks like this:
#model IEnumerable<DataApp.Models.Product>
#{
ViewData["Title"] = "Products";
Layout = "_Layout";
}
<table class="table table-sm table-striped">
<thead>
<tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th></tr>
</thead>
<tbody>
#foreach (var p in Model)
{
<tr>
<td>#p.Id</td>
<td>#p.Name</td>
<td>#p.Category</td>
<td>$#p.Price.ToString("F2")</td>
<td>
<form asp-action="Delete" method="post">
<a asp-action="Edit"
class="btn btn-sm btn-warning" asp-route-id="#p.Id">
Edit
</a>
<input type="hidden" name="id" value="#p.Id" />
<button type="submit" class="btn btn-danger btn-sm">
Delete
</button>
</form>
</td>
</tr>
}
</tbody>
</table>
<a asp-action="Create" class="btn btn-primary">Create New Product</a>
If I run the application and click the Edit or Create button, I don't get the Editor view. If I navigate in the browser to /Home/Edit, then the view is shown. What can be the problem?
You can find the complete source code for this chapter here:
Chapter 2
Please note, that I'm at the beginning of the chapter and the files in the source code may contain more, that I currently have, but according to the book, it should work on this stage too.
I have this controller which creates a List where T is a class model called GamingEvents.
public async Task<IActionResult> Index(DateTime start, DateTime end)
{
List<GamingEvents> gamingEventsListings = await sg.GenerateGameEventsSchedule();
ViewData["RangeStart"] = start;
ViewData["RangeEnd"] = end;
return View(gamingEventsListings);
}
In my view I generate this table to display the data:
#model List<GameManager.Models.GamingEvents>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.GameId)
</td>
<td>
#Html.DisplayFor(modelItem => item.GameName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DayNames)
</td>
</tr>
}
Now, I want to send all this data to another controller. So I made this form:
<form asp-controller="Scheduling" asp-action="ScheduleBlock" method="post">
<fieldset>
<button formaction="/Scheduling/ScheduleBlock/">Schedule Games</button>
</fieldset>
</form>
So I need the method, GenerateGameEventsFromSchedule(), to accept the two data properties I pass to the view, ViewData["RangeStart"] and ViewData["RangeEnd"].
So I started to write the controller:
[HttpPost]
public async Task<IActionResult> GenerateGameEventsFromSchedule(DateTime start, DateTime end)
{
foreach (event in GamingEvents)
{
//...do this
}
return View();
}
Obviously it's not finished.
My problem is, how would I pass the list of GamingEvents from my view above, to this new controller so that I can do additional processing on each item in the list?
Thanks!
What I want to do is a parametrized report, i would love to use SSRS or other fancy tools for this but it's sort of dangerous at this point because i don't really want to mess around with the company server and I dont have much time; Also If it's a tool it should be a free and light tool and i didn't find one by now.
So, my idea is making a simple controller with Index that will return a List to View according to parameters and the View will use that ViewModel as Model then the users can export that list to CSV or PDF, the problem is: MVC is asking for a real db model to complete the scaffolding, how can this be done then?
Controller (I call an stored proc here)
public class ReporteEntregasPresentacionController : Controller
{
private EntregaMedicamentosEntities db = new EntregaMedicamentosEntities();
public ActionResult Index(DateTime DateFrom, DateTime DateTo)
{
ReporteEntregasPresentacionViewModel rep = new ReporteEntregasPresentacionViewModel();
string sqlQuery = "[dbo].[spEntregasPorPresentacion] ({0},{1})";
Object[] parameters = { DateFrom, DateTo };
rep.LstEntregasPresentacionViewModel = db.Database.SqlQuery<ItemEntregasPresentacionViewModel>(sqlQuery, parameters).ToList();
return View(rep);
}
}
ViewModel:
public class ReporteEntregasPresentacionViewModel
{
public int index;
public List<ItemEntregasPresentacionViewModel> LstEntregasPresentacionViewModel;
}
public class ItemEntregasPresentacionViewModel {
public string idProducto { get; set; }
public string Descripcion { get; set; }
public string EntregasTotales { get; set; }
}
I don't have a View now but i should be something like this:
#model EntregaMedicamentos.Models.ReporteEntregasPresentacionViewModel
<link href="~/Content/css/styles.css" rel="stylesheet" />
#{
ViewBag.Title = "ReporteEntregasPresentacion";
}
<h2>ReporteEntregasPresentacion</h2>
#using (Html.BeginForm("Index", "Entrega", FormMethod.Post))
{
<div class="card text-white bg-secondary">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="input-group">
#Html.TextBox("DateFrom", ViewBag.currentFilter1 as DateTime?, new { #class = "form-control", placeholder = "Desde fecha", #readonly = "true", type = "datetime" })
#Html.TextBox("DateTo", ViewBag.currentFilter2 as DateTime?, new { #class = "form-control", placeholder = "Hasta fecha", #readonly = "true", type = "datetime" })
<button id="Submit4" type="submit" style='font-size:22px ;color:blue'><i class='fas fa-search'></i></button>
</div>
</div>
</div>
</div>
</div>
}
<br>
<table class="table table-striped ">
<tr class="table-primary">
<th>
Código
</th>
<th>
Producto
</th>
<th>
Entregas Totales
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.idProducto)
</td>
<td>
#Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Valor)
</td>
</tr>
}
</table>
I ended up creating a real table/model and then it worked fine with the viewmodel. Thanks.
This is not a repeated question am posting this question after trying all solutions.
I want to perform CRUD on a single View so I got this article
CRUD using SIngle View
It works fine but when I keep the text box empty then the Model is Valid returns false which is correct,after debugging it shows Name field is required but I cant see the error on the View.
Even #Html.ValidationSummary(true) is present in Begin Form
and #Html.ValidationMessageFor(model => model.Name)
So keeping the code short have used only one field
Model
public partial class tblClient
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
A class which handle multiple button
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Controller
public class EmpController : Controller
{
SampleEntities1 db = new SampleEntities1();
//
// GET: /Emp/
public ActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Name = db.tblClients.ToList();
tblClient objEmp = db.tblClients.Find(id);
return View(objEmp);
}
[HttpPost]
[HttpParamAction]
[ValidateAntiForgeryToken]
public ActionResult Create(tblClient objEmp)
{
if (ModelState.IsValid)
{
db.tblClients.Add(objEmp);
db.SaveChanges();
}
return RedirectToAction("Index");
}
[HttpPost]
[HttpParamAction]
[ValidateAntiForgeryToken]
public ActionResult Update(tblClient objEmp)
{
if (ModelState.IsValid)
{
db.Entry(objEmp).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index", new { id = 0 });
}
public ActionResult Delete(int id)
{
tblClient objEmp = db.tblClients.Find(id);
db.tblClients.Remove(objEmp);
db.SaveChanges();
return RedirectToAction("Index", new { id = 0 });
}
}
View
#using (Html.BeginForm())
{
<fieldset>
<legend><b>Emp Details</b></legend>
<table border="1" cellpadding="10">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
Action
</th>
</tr>
#foreach (var item in (IEnumerable<SingleVIewCrud.Models.tblClient>)ViewBag.Name)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.ActionLink("Edit", "Index", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
</fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<fieldset>
<legend> <b>Entry Screen</b></legend>
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<p>
<input type="submit" value="Create" name="Create"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
<input type="submit" value="Update" name="Update"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
</p>
</div>
</fieldset>
</div>
}
What is wrong that the validation error message is not displayed.
In both your Create() and Edit() POST methods, if ModelState is invalid, you just redirecting to the Index() view. You need to return the existing view -
if (!ModelState.IsValid()
{
return View(objEmp);
}
// save and redirect
db.tblClients.Add(objEmp);
db.SaveChanges();
return RedirectToAction("Index");
Side note: If you include the jquery.validate.js and jquery.validate.unobtrusive.js scripts, then you will also get client side validation and the POST methods will not even be hit - the validation messages will be displayed and the submit will be cancelled
I want to hide table based on conditions.I got error using this code.please help me to come out this error.
//IN Wicket :
<table class="jtrac jtrac-view" width="100%" wicket:id="request">
<tr>
<td ></td>
<td ></td>
</tr>
</table>
<table class="jtrac jtrac-view" width="100%" wicket:id="response">
<tr >
<td ></td>
<td ></td>
</tr>
</table>
I wrote java code like this.
WebMarkupContainer request = new WebMarkupContainer("request");
WebMarkupContainer response= new WebMarkupContainer("response");
add(request );
add(response);
if(time == null || time.equals("")) {
response.setVisible(false);
add(response);
}else {
request.setVisible(false);
add(request);
}
add(request());
add(response());
private WebMarkupContainer request() {
WebMarkupContainer r = new WebMarkupContainer("request") {
#Override
protected void onConfigure() {
super.onConfigure();
setVisible(StringUtils.isEmpty(time))
}
};
r.setOutputMarkupPlaceholderTag(true);
return r;
}
private WebMarkupContainer response() {
WebMarkupContainer r = new WebMarkupContainer("response") {
#Override
protected void onConfigure() {
super.onConfigure();
setVisible(StringUtils.isNotEmpty(time));
}
};
r.setOutputMarkupPlaceholderTag(true);
return r;
}
StringUtils is from Apache Commons: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html