I've created a modal component and that doesn't work - c#

I'm new in coding with ASP.NET Core. I created a CRUD functions in my application and then i decided to change some rules like Create New do not navigate to another tab it will be navigated to a component modal. So I did the steps that it shown in a tutorial but I didn't get a result .
Here's the page :
This is the code in index.cshtml:
#model IEnumerable<PermissionManagement.MVC.Models.Segment>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="PlaceHolderHere"></div>
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addSegment" asp-action="_SegmentModelPartial" data-url="#Url.Action("Create")"> Create </button>
And this is the code wrote it in SegmentModelPartial:
#model Segment
<div class="modal fade" id="addSegment">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addSegmentLabel">Modal title</h5>
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close">
<span>x</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="SName" class="control-label">Nom</label>
<input asp-for="SName" class="form-control" />
<span asp-validation-for="SName" class="text-danger"></span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group ">
<label asp-for="SRang" class="control-label">Rang</label>
<input asp-for="SRang" class="form-control" />
<span asp-validation-for="SRang" class="text-danger"></span>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
This is my code in site.js:
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data)){
PlaceHolderElement.find('.modal').modal('hide');
})
})
})
And finally this is the controller:
[HttpGet]
public IActionResult Create()
{
Segment seg = new Segment();
return PartialView("_SegmentModelPartial", seg);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Segment segment)
{
_context.Add(segment);
await _context.SaveChangesAsync();
return PartialView("_SegmentModelPartial", segment);
}

Related

Add a search bar in asp net mvc

I need to add a search bar on my index page, and the result of the research will be show on another page.
What I've tried:
The view
<form class="row contact-form rounded-pill link no-gutters" id="contact-form-data">
#using (Html.BeginForm("RechercheResto", "Client", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="col-12 col-lg-8 d-inline-block d-lg-flex align-items-center">
<div class="form-group">
<label><i class="lni lni-restaurant" aria-hidden="true"></i></label>
<input type="text" name="nomResto" placeholder="Nom du restaurant" class="form-control">
</div>
</div>
<div class="col-12 col-lg-4">
<i class="fa fa-spinner fa-spin mr-2 d-none" aria-hidden="true"></i>
<input type="submit" class="btn main-btn rounded-pill w-100 h-100 contact_btn" value="Rechercher le restaurant" />
</div>
}
</form>
The controller
[ValidateAntiForgeryToken]
public ActionResult RechercheResto(string nomResto)
{
var restoList = from r in db.Restaurants select r;
if (!string.IsNullOrEmpty(nomResto))
{
restoList = restoList.Where(r => r.name.Contains(nomResto));
}
return View(restoList.ToList());
}
At the time of returning View(restoList.ToList()) you can add viewname in first parameter and second will be your result.ToList().
Thanks for your help. I've just find the solution. The problem was the I put before the BeginForm.
The working code look like that
#using (Html.BeginForm("RechercheResto", "Client", FormMethod.Post, new { #class= "row contact-form rounded-pill link no-gutters"}))
{
#Html.AntiForgeryToken()
<div class="col-12 col-lg-8 d-inline-block d-lg-flex align-items-center">
<div class="form-group">
<label><i class="lni lni-restaurant" aria-hidden="true"></i></label>
<input type="text" name="nomResto" placeholder="Nom du restaurant" class="form-control">
</div>
</div>
<div class="col-12 col-lg-4">
<i class="fa fa-spinner fa-spin mr-2 d-none" aria-hidden="true"></i>
<input type="submit" class="btn main-btn rounded-pill w-100 h-100 contact_btn" value="Rechercher le restaurant" />
</div>
}

On After Render a Modal razor component start a JavaScript

I have a blazor app with an razor component as modal open by
Open the modal.razor
<ModalScan #ref="ModalScan"><p>Scanner</p></ModalScan>
<button class="btn btn-primary" #onclick="ScanStart">Start Scann</button>
#code{
ModalScan ModalScan;
void ScanStart()
{
ModalScan.Show();
}
}
the modal.razor
#if (_Show)
{
<div class="modal fade show" style="display: block;">
<div class="modal-dialog" style="width: 90%;" #>
<div id="modal_fullscreen" class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Scanner</h5>
<button type="button" class="close" data-dismiss="modal" #onclick="Show">×</button>
</div>
<div class="modal-body">
<form>
<div class="container">
<div class="form-row">
<div id="loadingMessage">Unable to access video stream </div>
<canvas style="width: 100%;" id="canvas" hidden></canvas>
<div id="output" hidden>
<div id="outputMessage">No detected.</div>
<div hidden>
<input type="text" id="outputData" value="#CurrentValue"
#onchange="#((ChangeEventArgs __e) => CurrentValue = __e.Value.ToString())" />
</div>
</div>
</div>
<div class="form-row">
<button type="button" class="btn btn-dark" #onclick="ScanResume">Scan</button>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" #onclick="Show">Abort</button>
<button type="button" class="btn btn-primary" #onclick="saveChanges">Ok</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal-backdrop fade show"></div>
}
After this modal.razor is load, i will start a js-Script.
I can only start with a button, then the DOM is not loading when
i invoke the Javascript on the Show() void.
On a razor page works it with:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("startScanner");
}
}
public async void Show()
{
_Show = !_Show;
if (_Show)
{
}
}
but not on the modal.
Is there any event to check if modal is load complete from razor componetes in my modal?

Refresh PartialView in MVC Controller

I'm trying to refresh my Partial View after submitting a form which will be processed in my controller. The problem is that whenever I try to refresh it form my controller, I get redirected to a blank page with content from the Partial View.
Partial View
#model Smarty.Viewmodels.BugViewModel
<div class="modal fade" id="bugModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Bug Reporting Tool</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span>×</span>
</button>
</div>
<form asp-controller="Smarty" asp-action="SendBugReport" enctype="multipart/form-data">
#if (!string.IsNullOrWhiteSpace(ViewBag.message))
{
if (!ViewBag.IsError)
{
<span class="border border-success text-success">#ViewBag.message</span>
}
else
{
<span class="border border-danger text-danger">#ViewBag.message</span>
}
}
<div class="modal-body">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
<label asp-for="FormFile" class="control-label"></label><br />
<input asp-for="FormFile" type="file" />
<span asp-validation-for="FormFile" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
<button type="submit" id="BugReportBtn" class="btn btn-success">Bug Report senden</button>
</div>
</form>
</div>
</div>
</div>
Controller
public async Task<IActionResult> SendBugReport(BugViewModel viewModel)
{
//Process Form
return PartialView("BugModal", viewModel);
}
Thanks in advance!
I get redirected to a blank page with content from the Partial View.
That is expected because you use return PartialView() which will return the simple partial html to render it into the view.
I want to refresh the Partial View with content like Error Messages, Success messages etc
You could not get #ViewBag.message from the SendBugReport action, it is passed from the action of main page.
As the comment has said that, first of all, you could use ajax to submit the form to SendBugReport action.Then the action return message and isError json data to ajax success function. Finally, you render message on the view based on the value of isError:
1.Partial View (Views/Shared/BugModal.cshtml)
#model BugViewModel
<div class="modal fade" id="bugModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Bug Reporting Tool</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span>×</span>
</button>
</div>
<form id="myForm" asp-controller="Smarty" asp-action="SendBugReport" enctype="multipart/form-data">
<div id="result"></div>
<div class="modal-body">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
<label asp-for="FormFile" class="control-label"></label><br />
<input asp-for="FormFile" id="FormFile" name="FormFile" type="file" />
<span asp-validation-for="FormFile" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
<button type="button" id="BugReportBtn" class="btn btn-success">Bug Report senden</button>
</div>
</form>
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script>
$('#BugReportBtn').on('click', function (event) {
var url = "/Smarty/SendBugReport";
var description = document.getElementById("Description").value;
var fileInput = $('#FormFile')[0];
var formFile = fileInput.files[0];
var formData = new FormData();
formData.append("Description", description);
formData.append("FormFile", formFile);
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: "json",
processData:false,
contentType: false,
success: function (data) {
if (!data.isError) {
$("#result").html("<span class='border border-success text-success'>" + data.message + "</span>");
} else {
$("#result").html("<span class='border border-danger text-danger'>" + data.message + "</span>");
}
$('#bugModal').modal('show');
}
});
});
</script>
2.Action
[HttpPost]
public async Task<JsonResult> SendBugReport(BugViewModel viewModel)
{
//Process Form
string message;
bool isError;
//set data to message and isError
return Json(new { message, isError });
}

ASP.NET Core 2.1 Unobtrusive Ajax Validation Not Working With Partial View Form Swap

I've spent several hours combing Stackoverflow and other sites trying everyone's solutions with no luck so far. I'm sure I've missed something, but I can't see it. Hopefully you can point me to a fix.
I have an initial form inside a partial view that is rendered into a parent view whose validation works fine. Once the form is submitted via Ajax replace, I return either a login or registration partial view with a new form in the response. This second form will not display the model validation errors when an incomplete form is submitted and the same partial view is returned.
Thanks in advance for any tips you can offer to bring an end to this insanity!
Parent View Section
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="panel panel-primary" id="formData">
#await Html.PartialAsync("_UserNamePartial", new UserNameViewModel())
</div>
</div>
</div>
Working Rendered Partial View
<div class="panel-heading">
<h3 class="panel-title">Let's Start With Your E-mail Address</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<form asp-controller="Account" asp-action="IsAccountValid" data-ajax="true" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#formData">
#Html.AntiForgeryToken()
<div class="form-group">
<label for="UserName">Your Email Address</label>
<div class="input-group">
<input type="text" id="UserName" name="UserName" class="form-control" placeholder="Your email address" />
<div class="input-group-btn">
<button type="submit" id="btnGetStarted" class="btn btn-primary">Get Started</button>
</div>
</div>
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</form>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
</div>
</div>
</div>
Initial Validation Controller Action
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult IsAccountValid(UserNameViewModel model)
{
if (!ModelState.IsValid)
return PartialView("../Home/_UserNamePartial", model);
AccountRepository accountRepository = new AccountRepository(ConnectionConfig.InshoraDev);
AuthName match = accountRepository.GetAuthName(model.UserName);
if (match != null)
{
ModelState.Clear();
LoginViewModel loginModel = new LoginViewModel()
{
UserName = model.UserName
};
return PartialView("_UserLoginPartial", loginModel);
}
ModelState.Clear();
SignUpViewModel signupModel = new SignUpViewModel()
{
UserName = model.UserName,
};
return PartialView("_UserSignUp", signupModel);
}
Login Partial View (Validation Error Display Not Working)
#model Inshora.Models.Account.LoginViewModel
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="panel-heading">
<h3 class="panel-title">Log Into Your Account</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<form id="login-form" asp-controller="Account" asp-action="Login" method="post" role="form" style="display: block;"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="formData" data-ajax-complete="AcctLib.Login.Events.onComplete">
#Html.AntiForgeryToken()
<div class="form-group">
<input type="text" name="UserName" id="UserName" tabindex="1" class="form-control" placeholder="Email Address" value="#Model.UserName">
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="password" name="Password" id="Password" tabindex="2" class="form-control" placeholder="Password">
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group text-center">
<input type="checkbox" tabindex="3" class="" name="RememberMe" id="RememberMe">
<label for="RememberMe"> Remember Me</label>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-primary" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
<a id="PasswordReset" asp-controller="Account" asp-action="PasswordReset" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#formData" tabindex="5" class="inshora-forgot-password">Forgot Password?</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
AcctLib.Login.Init();
})
</script>
LoginViewModel
public class LoginViewModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public bool RememberMe { get; set; }
}
Client Side Initialization Code
AcctLib.Login.RebindForm = function() {
$('form').each(function (i, f) {
$form = $(f);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
});
}
AcctLib.Login.Init = function () {
AcctLib.Login.RebindForm();
$('#UserName').focus();
}
Update
I have updated the parent page (index.cshtml) to the following and it still doesn't display the messages.
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="panel panel-primary" id="formData">
#await Html.PartialAsync("_UserNamePartial", new UserNameViewModel())
</div>
</div>
</div>
#section Scripts
{
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
The problem was that I had not used the asp-for tag helpers. Those helpers are responsible for generating the data-* attributes needed by the unobtrusive validation parser. Once I started using them it started working. Thank you to everyone who tried to help.
Corrected View
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<form id="login-form" asp-controller="Account" asp-action="Login" method="post" role="form"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#formData">
#Html.AntiForgeryToken()
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName"></label>
<input asp-for="UserName" class="form-control" placeholder="Email Address"/>
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" placeholder="Password"/>
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group text-center">
<input asp-for="RememberMe" />
<label asp-for="RememberMe"> Remember Me</label>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-primary" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
<a id="PasswordReset" asp-controller="Account" asp-action="PasswordReset" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#formData" tabindex="5" class="inshora-forgot-password">Forgot Password?</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
if (!ModelState.IsValid)
return PartialView("..\\Home\\_UserNamePartial", model);
pretty sure this violates pathing
if(!ModelState.IsValid)
return PartialView("../Home/_UserNamePartial", model);
Cut renderPartial link and paste to before #script section, like below:
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
#section Scripts
{
}

Partial View Not Rendering Inside View

I have a partial view inside another partial view which, when first running the application loads as expected, but when you click to reload the view to push a model into it, it then renders as it's own completely separate view as if it weren't a partial.
I'm calling it inside an Ajax Form like so (On the Action link click, the _GetSearchModal method):
<div id="modelSearch">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<i class="fa fa-search"></i> Search by Model / Manufacturer
</h3>
</div>
<div class="panel-body">
#using (Ajax.BeginForm("_GetSearch", "Home", new AjaxOptions() {UpdateTargetId = "modelSearch"}))
{
#Html.AntiForgeryToken()
<div class="input-group">
#Html.TextBox("search", null, new {id = "name", #class = "form-control", placeholder = "Please enter a manufacturer or model"})
<span class="input-group-btn">
<button id="search" class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
if (Model != null)
{
<div id="searchResults" class="fade-in two">
#foreach (var s in Model)
{
<div class="result">
#switch (s.ResultType)
{
case "Man":
#s.Manufacturer
break;
case "Mod":
#Html.ActionLink(s.Manufacturer + Html.Raw(s.Model), "_GetSearchModal", "Home", new {id = s.MachineId}, new {toggle = "modal", data_target = "#MachineModal"})
<img src="~/Images/General/Tier/#(s.TierId).png" alt="Tier #s.TierId"/>
break;
}
</div>
}
</div>
}
}
</div>
</div>
</div>
<!-- Product Modal -->
<div class="modal fade" id="MachineModal" tabindex="-1" role="dialog" aria-labelledby="MachineModalLabel">
#Html.Partial("_SearchModal", new MachineModal())
</div>
And the view itself should load a different view model (MachineModal):
#model SpecCheck.Portals.Web.UI.ViewModels.MachineModal
#if (Model != null)
{
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="MachineModalLabel">#Model.Manufacturer #Model.Model</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<img src="~/Images/#Model.Manufacturer/logo.png" alt="#Model.Manufacturer" /><br />
Wiki
</div>
<div class="col-md-6">
#Model.Catagory1 | #Model.Category2<br /><br />
<span class="modal-em">Region: </span> #Model.Region<br />
<span class="modal-em">Status: </span>#Model.Status<br />
<span class="modal-em">Spec Date: </span>#Model.SpecDate
</div>
</div>
</div>
<div class="modal-footer">
View
Quick Compare
Compare
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
}
And the action to do this in the "Home Controller" is:
public ActionResult _GetSearchModal(string machineId)
{
using (var db = new SpecCheckDbContext())
{
MachineModal machine = new MachineModal();
var searchHelper = new SearchHelper(db);
//Get Machine Details
var dbResults = searchHelper.SearchModal(Convert.ToInt32(machineId));
machine.Model = dbResults.Model;
machine.Catagory1 = dbResults.Catagory1;
machine.Category2 = dbResults.Category2;
machine.Manufacturer = dbResults.Manufacturer;
machine.Region = dbResults.Region;
machine.SpecDate = dbResults.SpecDate;
machine.Status = dbResults.Status;
machine.MachineId = dbResults.MachineId;
machine.ManufacturerId = dbResults.ManufacturerId;
var model = machine;
return PartialView("_SearchModal", model);
}
}
First thing I checked was the scripts, they're all in place when the layout page loads so it's not a script issue. Not sure what to change to even try at this point so any suggestions welcome.
In the ajax form:
_GetSearch => _GetSearchModal(name of the action)
Try to return machine to the partial view? Maybe see in the View hierarchy, is there is second _SearchModal partial view, that gets returned?

Categories