How to pass button value from a modal window (that uses partial view) to the parent view - razor

here is the button on the partial view,
<button type="button" name="btnid" id="bparentid" value="#item.Itemid " class="btn btn-success" onclick="alert(#item.Itemid)">Select</button>
Just to check if it holds the value I put razor alert function, and I want the button value to be passed to the parent view on button click using this hidden input form in the parent view
<input asp-for="Itemid" type="hidden" value=" #item.Itemid" />
More detail:
I have two tables for recording children and their parents separately,
Here is the Model
public class Children
{
[Key]
public int ChildID { get; set; }
[Required] [StringLength(50)]
public string FirstName { get; set; }
[ForeignKey("Parentid")]
public virtual Parent Parent { get; set; }
}
public class Parent
{
[Key]
public int Parentid { get; set; }
public string FullName { get; set; }
public virtual IEnumerable<Children> Children { get; set; }
}
And here is the Create method controller for posting new children record with their parent information:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ChildID,FirstName")] Children children, int existingParentid,
[Bind("Parentid,FullName")] Parent parent, bool existingparent)
{
if (ModelState.IsValid)
{
if (existingparent)
{
children.Parentid = existingParentid;
_context.Add(children);
await _context.SaveChangesAsync();
return View(children);
}else
_context.Add(children);
await _context.SaveChangesAsync();
_context.Add(parent);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(children);
}
Here is the controller method for the modal partial view
public async Task<IActionResult> ModalAction()
{
var MyDbContext = _context.Children.Include(C => C.Parent);
return PartialView(await MyDbContext.ToListAsync());
}
And here is the view for the Create method
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
#Html.ActionLink("Select Existing Parent", "ModalAction", "Children", null, new { #class = "btn btn-flat margin",
data_target = "#searchparent", data_toggle = "modal" })
<input asp-for="Parentid" type="hidden" value=" " />
<div class="modal fade" id="searchparent">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Parent.FullName" class="control-label"></label>
<input asp-for="Parent.FullName" class="form-control" />
<span asp-validation-for="Parent.FullName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
Here is the modal partial view
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Search for Parent data table </h4>
</div>
<div class="modal-body">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
<button type="button" name="bparentid" id="bparentid" value="#item.ChildID" class="btn btn-block btn-success btn-xs"
onclick="alert(#item.ChildID)">
Select
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
The Question:
How can I pass the #item.ChildID value from the partial view to the Create view which will then pass it as hidden value to the create controller

Since you are trying to change the value of the input field after the page has loaded, this needs to happen inside the user's browser, so Razor which runs server-side can't help. But you can accomplish what you want using javascript:
//First add an ID to your hidden input
<input id="my-input" ... />
//Second add the following onclick to your button:
<button onclick="document.getElementById('my-input').value = this.value" ...></button>

Related

An expression tree may not contain a dynamic operation -mvc

I use two model in a single view so for that i make a class in i which I put both model.But when i use it, it gives me error.
Model:
namespace Laboratory_Management.Models
{
public class PatientandTest
{
public PatientTbl PatientTbl { get; set; }
public PatientTestTbl PatientTestTbl { get; set; }
}
}
View:
#model Laboratory_Management.Models.PatientandTest
#{
ViewData["Title"] = "Index1";
}
<h1>Index1</h1>
<h4>PatientTbl</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Index1" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="PatientTbl.PName" class="control-label"></label>
<input asp-for="PatientTbl.PName" class="form-control" id="PName" />
<span asp-validation-for="PatientTbl.PName" class="text-danger"></span>
</div>
</form>
</div>
</div>

How can i use the value from a textbox component in blazor?

Im trying to create a textbox component to recicle code, but i cant get the value from the textbox in a page. I only need to get the TextBox value from the component to use it into other pages.
this is the TextBox component :
<style>
.textbox-parameters{
background: Red;
}
</style>
#if (!string.IsNullOrWhiteSpace(Label))
{
<label for="#Id">#Label</label>
}
<div class="input-group mb-3 " >
<input type="text" class="form-control textbox-parameters" id="#Id" #bind="#CurrentValue">
</div>
#code {
[Parameter] public string? Label { get; set; }
[Parameter] public string? Id { get; set; }
private string CurrentValue {get;set;} = "";
}
and im trying to use there:
<div class="container-fluid">
<div class="row">
<div class="col-sm">
<label >Proyecto:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" id="basic-url" aria-describedby="basic-addon3">
</div>
</div>
<div class="col-sm">
<p class="rcorners2">Lista modelos</p>
</div>
<div class="col-sm">
<p class="rcorners2">Lista Iteraciónes</p>
</div>
<div class="col-sm">
<p class="rcorners2">Imagen Semilla</p>
</div>
<div class="col-sm ">
<div class="row">
<div class="col-sm">
<label>Ancho</label>
<div class="input-group mb-3">
<div class="input-group-prepend"></div>
<input type="text" class="form-control textbox-parameters" id="basic-url" aria-describedby="basic-addon3">
</div>
</div>
<div class="col-sm">
<TextBox Id="Alto" Label="Alto" CurrentValue="#alto" />
</div>
<label>Texto: #alto</label>
</div>
<div class="row">
<div class="col-sm text-center">
<label>Numero Imágenes</label>
<div class="input-group mb-3 " >
<input type="text" class="form-control textbox-parameters" id="basic-url" aria-describedby="basic-addon3">
</div>
</div>
</div>
</div>
<div class="col-sm">
<button type="button" class="btn btn-outline-success">Generar</button>
</div>
</div>
</div>
#code{
string alto="";
}
Sorry for my extra text but StackOverflow need more details but thats my only problem with my code. thanks.
You need to set up binding correctly - i.e. set up the Value and ValueChanged parameters on the component.
Here's TextBox:
<style>
.textbox-parameters{
background: Red;
}
</style>
#if (!string.IsNullOrWhiteSpace(Label))
{
<label for="#Id">#Label</label>
}
<div class="input-group mb-3 " >
<input type="text" class="form-control textbox-parameters" id="#Id" value="#Value" #onchange="this.OnChange">
</div>
#code {
[Parameter] public string Value {get;set;} = "";
[Parameter] public EventCallback<string> ValueChanged {get;set;}
[Parameter] public string? Label { get; set; }
[Parameter] public string? Id { get; set; }
private void OnChange(ChangeEventArgs e)
{
ValueChanged.InvokeAsync(e.Value.ToString());
}
}
Note we've bound the value to Value and the change event to OnChange which then invokes ValueChanged.
And a test page:
#page "/"
<TextBox #bind-Value="#this.Value" />
<div>
Value = #this.Value
</div>
#code {
private string Value { get; set; } = "Fred";
}
#bind-Value tells the Razor pre-compiler to bind to Value to set the value and ValueChanged to update the bound field/property.

How to pass parameters from Modal form to Spring Controller with thymeleaf or Jquery?

Anyone can help me? I made a Modal with a form to update a database. I receive data from Mysql DB but when i click on submit, the modal closes, but new parameters don't pass to the Spring controller... Where is the error?
Model class:
#Entity
#Table(name = "generi")
public class Genere {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idGenere;
#Column
private String nomeGenere;
public Genere () {}
/**
* #param idGenere
* #param nomeGenere
*/
public Genere(int idGenere, String nomeGenere) {
setIdGenere(idGenere);
setNomeGenere(nomeGenere);
}
...and GETTERS and SETTERS
Service Class
#Service
public class GenereService {
#Autowired
private GenereRepository genereRepository;
public List<Genere> getGeneri(){
List<Genere> listGeneri = new ArrayList<Genere>();
genereRepository.findAll().forEach(listGeneri::add);
return listGeneri;
}
public void inserisciNuovoGenere(Genere genere) {
genereRepository.save(genere);
}
public void cancellaGenere(int idGenere) {
if (genereRepository.findById(idGenere) != null) {
genereRepository.deleteById(idGenere);
}
}
public void updateGenere (Genere genere) {
if (genereRepository.findById(genere.getIdGenere()) != null )
genereRepository.save(genere);
}
Controller
#Controller
public class GenereController {
#Autowired
private GenereService genereService;
#GetMapping("/generi")
public String getGeneri (Model model) {
model.addAttribute("newGen", new Genere());
model.addAttribute("generi", genereService.getGeneri());
return "generi";
}
#PostMapping("/generi")
public String postGeneriInsert(#ModelAttribute (name = "newGen") Genere newGen) {
genereService.inserisciNuovoGenere(newGen);
return "redirect:/generi";
}
#GetMapping("/generi/delete/{idGenere}")
public String getGenereDelete (#PathVariable int idGenere) {
genereService.cancellaGenere(idGenere);
return "redirect:/generi";
}
#PostMapping("/updateGen")
public String postUpdateGenere(#ModelAttribute Genere genere) {
genereService.updateGenere(genere);
return "redirect:/generi";
}
generi.html
<body>
<th:block th:include="fragments/update_scripts.html"></th:block>
<div class="container">
<div th:replace="fragments/common :: Logout"></div>
</div> <!-- end container -->
<div class="container login">
<h3>Gestione Generi</h3>
<form th:object="${newGen}" th:action="#{/generi}" method="post">
<div class="form-group">
<label for="gen">Aggiungi un nuovo genere</label>
<input type="text" id="gen" class="form-control" th:field="*{nomeGenere}" required="required">
</div>
<input type="submit" class="btn btn-primary" value="Aggiungi">
</form>
<br><br>
<table class="table table-stripped">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Genere</th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="genere : ${generi}">
<td th:text="${genere.idGenere}"></td>
<td th:text="${genere.nomeGenere}"></td>
<td>
<button type="button"
class="btn btn-info btn-sm"
data-toggle="modal"
data-target="#updateGen"
th:attr="data-id=${genere.idGenere},
data-lab=${genere.nomeGenere}">Modifica</button>
<button type="button"
class="btn btn-outline-danger btn-sm"
data-toggle="modal"
data-target="#deleteConfirm"
th:attr="data-id=${genere.idGenere},
data-lab=${genere.nomeGenere}">Elimina</button>
</td>
</tr>
</tbody>
</table>
</div>
<div th:replace="fragments/common :: deleteConfirm"></div>
<div th:replace="fragments/update_modals :: updateGen"></div>
<div th:replace="fragments/common :: bootstrap"></div>
</body>
update_modal.html
<!-- modal Update Genere -->
<div class="modal fade" id="updateGen" tabindex="-1" th:fragment="updateGen" aria-labelledby="updGenModal">
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updGenModal">Modifica il Genere</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>
<p id="Prova">Modal di Prova: </p>
</div>
<form th:action="#{/updateGen}" th:object="${genere}" method="post">
<input type="hidden" class="form-control" id="idGen" name="idGenere" value=""/>
<div class="form-group">
<label for="modGen" class="col-form-label">Genere</label>
<input type="text" class="form-control" id="modGen" name="nomeGenere" th:field="*{nomeGenere}" value="" required="required" />
</div>
</form>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-outline-warning" id="btnUpdGen" value="Aggiorna" data-dismiss="modal" />
<button type="button" class="btn btn-outline-secondary" data-dismiss="modal" >Annulla</button>
</div>
</div>
</div>
</div>
<!-- End modal Update Genere -->
Update_script
<script >
$(document).ready(function() {
$('#updateGen').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var label = button.data('lab');
var modal = $(this);
$('#Prova').html('Modifica -> ' + label);
modal.find('.modal-body #modGen').val(label);
})
});
</script>
And that's all...
Sorry for my long post, and if I made some errors creating it... but it's my first time on StackOverflow...

display div on failed login in html, using Umbraco amd MVC

I have a div in which I want to display a login error message only when a failed login is attempted.
The call to do the login is
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult HandleLoginSubmit(LoginModel model)
{
if (!ModelState.IsValid)
{
return CurrentUmbracoPage();
}
if (Membership.ValidateUser(model.Username, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Username, createPersistentCookie: false);
return Redirect(model.ReturnUrl ?? "/login");
}
else
{
ModelState.AddModelError(nameof(model.Username), "Incorrect UserName");
ModelState.AddModelError(nameof(model.Password), "Incorrect password");
return CurrentUmbracoPage();
}
}
and the div is
<div class="col-lg-10 alert alert-danger justify-content-around mt-2" style="margin-left:auto; margin-right:auto;">
<div class="container">
<div class="alert-icon">
<i class="material-icons">error_outline</i>
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i class="material-icons">clear</i></span>
</button>
<b>Error Alert: </b>
</div>
</div>
What should I return from the call if the login is successful, and how do I reference it in the html?
Seems like your version of Umbraco is 7.x. With the following controller name and the method name, for example:
public class RecoverUserDataSurfaceController : SurfaceControllerBaseController
{
[HttpPost]
public ActionResult SubmitEmailForPasswordReset(UserModel model)
{
if (!ModelState.IsValid)
{
return CurrentUmbracoPage();
}
bool success = _recoverUnpwWorkflow.RecoverPasswordSubmitEmail(model);
TempData.Add("Success", success);
return RedirectToCurrentUmbracoPage();
}
}
The html should be:
<form method="post" id="form-lost-password">
#using(Html.BeginUmbracoForm<UmbracoApp.Controllers.RecoverUserDataSurfaceController>("SubmitEmailForPasswordReset"))
{
<div class="text-field validate-email required">
<label for="EmailAddress">Email Address</label>
#Html.ValidationMessageFor(x => x.EmailAddress)
#Html.TextBoxFor(x => x.EmailAddress, new { #placeholder = "name#domain.com" })
</div>
<div class="submit-field">
<input type="submit" value="Submit" title="Submit" class="btn-default" />
</div>
}
</form>
Hope that helps.

I am trying to form relationship for models between News and its Category

I want to have News can have multiple NewsCategories. one-to-many relationship. I am trying to pass categories to MVC controller (post create action). But ModelState.IsValid is always failed. I think my post action does not get selected values from view somehow..
Please help my friend geeks!
I have News.cs:
public class News
{
public long NewsId { get; set; }
public ICollection<NewsCategory> NewsCategories { get; set; }
}
I have NewsCategory.cs:
public class NewsCategory
{
public int NewsCategoryId { get; set; }
public long NewsId { get; set; }
public string Title { get; set; }
}
I have NewsController.cs:
// GET: News/Create
public IActionResult Create()
{
List<NewsCategory> newsCategories = new List<NewsCategory>();
newsCategories = (from s in _context.NewsCategory select s).OrderBy(m => m.Title).ToList();
newsCategories.Insert(0, new NewsCategory { NewsCategoryId = 0, Title = "Select" });
ViewBag.NewsCategories = newsCategories;
return View();
}
And this is Create Post action:
// POST: News/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Title,Content,NewsTagName1,NewsTagName2")]News news, List<IFormFile> files)
{
if (ModelState.IsValid)
{
_context.Add(news);
var newsCategories = news.NewsCategories;
foreach(var item in newsCategories)
{
item.NewsId = news.NewsId;
_context.NewsCategory.Add(item);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(news);
}
But always fails on 'Model.IsValid'
Here is snapshot of what's in object News.
Here is the error message:
Here is News create view:
#model Carsubfax.Models.News
#{
ViewData["Title"] = "Create";
}
<form asp-action="Create" id="comment-form" name="comment-form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" id="txtTitle" autocomplete="off" required="required" placeholder="Enter your news title." />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<div class="form-group">
<label class="control-label">News Cover Image<span style="color:red">*</span></label>
<input type="file" name="files" required />
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<div class="form-group">
<label class="control-label">News Category</label>
<select asp-for="NewsCategories" class="form-control" asp-items="#(new SelectList(ViewBag.NewsCategories, "NewsCategoryId", "Title"))" required="required"></select>
</div>
<div class="col-md-10 col-md-offset-1">
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" onclick="return btnSubmit_clik();">POST</button>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<div class="form-group text-center">
<a asp-action="Index">Back to List</a>
</div>
</div>
</div>
</form>
</div>
</div>