can you help on this please :
The submit button is not working in simple ASP MVC page after trying to open the bootstrap modal , using AJAX.ActionLink, but when I try top open directly (without AJAX.ActionLink) it is working and then calling the controller's action at server side : here is the code
Main Page : index.cshtml
#model IEnumerable<TestQuestionsAnswers.Models.Question>
#{
ViewBag.Title = "Index";
}
<script>
function ShowPopup() {
$("#divmodal").attr('data-toggle', 'modal');
$('#divmodal').modal('show');
}
</script>
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
#Ajax.ActionLink("Validate Data!", "Edit1", "Question", new { id = 1 }, new AjaxOptions { UpdateTargetId = "divresponse", OnComplete = "ShowPopup" }, new { #class = "btn btn-info btn-sm" })
</p>
<!-- Modal -->
<div id="divmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Question</h4>
</div>
<div class="modal-body">
<div class="container" id="divresponse">Data is here....</div>
<input type="submit" class="btn btn-info" name="btnsubmit" value="Save">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Please Note: from the code above I am using this :
#Ajax.ActionLink("Validate Data!", "Edit1", "Question", new { id = 1 }, new AjaxOptions { UpdateTargetId = "divresponse", OnComplete = "ShowPopup
to open the modal window .
the Edit.chtml:
#model TestQuestionsAnswers.Models.QuestionEditView
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm("Save", "Question", FormMethod.Post))
{
<input type="submit" class="btn btn-info" name="btnsubmit" value="Save" >
}
and the controller 's action which supposed to reach is :
[HttpPost]
public ActionResult Save(string btnsubmit, TestQuestionsAnswers.Models.QuestionEditView questedit)
{
if (btnsubmit == "Save")
{
List<Answer> UpdatedAnswers=questedit.Answers;
dbaccess.SaveEditQuestionsBy(questedit);
}
return RedirectToAction("Index");
}
I appreciate your help
I dont know you have installed unobtrusive-ajax package or not
but if not first go to manage nudget package -> search ajax and install Microsoft.jquery.unobtrusive-ajax.js package
then give this reference in your cshtml
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
then put debugger in controller and check whether method is firing or not.
Related
I am making a searchfield which triggers a request function returning partial view and according to result I want to show the response in partial view under the searchfield in the same page. User writes something to textfield and clicks the search button then under them result shows. I get the result but my partialview is opening in another page instead of under the searchfield in the same page. Also looks like my onClick function does not trigger.
My main View:
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-6 p-3">
<form class="form-group" method="post" action="/Books/BookDetail">
<div class="input-group">
<input type="text" name="barcodes" class="form-control bg-light border-0 small bg-gray-200" placeholder="Kitap Barkodunu giriniz..." aria-label="Search" aria-describedby="basic-addon2">
<button class="btn btn-primary" type="submit" id="myBtn" name="myBtn" onclick="showBook">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</form>
</div>
<br />
<div id="partialContent">
</div>
</div>
</div>
<script>
function showBook() {
$('#partialContent').load("/Controllers/BooksController/BookDetail");
}
</script>
Book Detail Controller:
public IActionResult BookDetail(string barcodes)
{
var request = $"?barcodes={barcodes}";
var products = _httpTool.HttpGetAsync<List<Products>>($"{AppSettings.ApiUrl}/GetProducts{request}");
if(products.Result.Count != 0)
{
ViewBag.result = "Success";
var product = products.Result[0];
return PartialView("_BookDetailPartial", product);
}
else
{
ViewBag.result = "Failed";
return View("AddBook");
}
}
_BookDetailPartial:
<div>
<h4>PartialCame</h4>
<br />
<h5>#Model.Author</h5>
</div>
What is the problem here?
Thanks in advance!
onclick="showBook"
should be
onclick="showBook()"
And this path appears to be wrong: "/Controllers/BooksController/BookDetail" it should most likely be "/Books/BookDetail?barcodes=barcode"
I'm not sure what you mean about the partial view loading in another page. Could you give some more detail please?
I have to generate file depending on input (checkboxes) and download it:
[HttpGet]
public FileResult GenerateFormatSettingsFile(IEnumerable<string> values)
{
var content = FileSettingsGenerator.Generate(values);
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine(content);
tw.Flush();
tw.Close();
return File(memoryStream.GetBuffer(), "text/plain", "file.txt");
}
And on my view this:
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
$(document).ready(function() {
$("#GenetateFormatSettingsFile").click(function() {
var f = {};
var checkboxes = [];
$('input:checked').each(function() {
checkboxes.push($(this).attr("value"));
});
f.url = '#Url.Action("GenerateFormatSettingsFile", "Home")';
f.type = "GET";
f.dataType = "text";
f.data = { values: checkboxes},
f.traditional = true;
f.success = function(response) {
};
f.error = function(jqxhr, status, exception) {
alert(exception);
};
$.ajax(f);
});
});
</script>
The problem is the download doesn't start. How could I fix it?
If I do it with Html.ActionLink, the download starts, but I can't pass the values of checkboxes which is done by my ajax function above
Thanks!
Edit - that's how my check-boxes looks like:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal" id="formatterSettings" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Settings</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="defaultG">To default view</label>
<input class="form-control" type="checkbox" value="Default" id="defaultG">
</div>
<div class="form-group">
<label for="extendedG">To extended view</label>
<input class="form-control" type="checkbox" value="Extended" id="extendedG">
</div>
/div>
</form>
</div>
<div class="modal-footer">
<div class="col-md-6">
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
#Html.ActionLink("Generate!", "GenerateFormatSettingsFile")
</div>
<div class="col-md-6">
<a class="btn btn-primary" data-dismiss="modal" >Generate From Code</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Put a submit button in your form and POST your form synchronously (without ajax).
when a form is posted, values of all input elements (TextBoxes, CheckBoxes, ...) are sent to the server (with the request) and you don't need to do anything.
How do I get the get method called aidx parameter by post method?
When I start with the current code, it says that it is not defined.
aidx is the primary key, and I want to assign that primary key to the Family column.
<div id="blogpost" class="inner-content">
<form id="formdata"action="#Url.Action("Detail", "Board")" method="post" enctype="multipart/form-data">
<section class="inner-section">
<div class="main_blog text-center roomy-100">
<div class="col-sm-8 col-sm-offset-2">
<div class="head_title text-center">
<h2>#Html.DisplayTextFor(m => m.Article.Title)</h2>
#Html.HiddenFor(m => m.Article.ArticleIDX)
<div class="separator_auto"></div>
<div class="row">
<div class="col-md-8" style="margin-left:6%;">
<p>
<label>분 류 : </label>
#Html.DisplayTextFor(m => m.Article.Category)
</p>
</div>
<div class="col-md-8" style="margin-left:5%;">
<p>
<label>작성자 : </label>
#Html.DisplayTextFor(m => m.Article.Members.Name)
</p>
</div>
<div class="col-md-8" style="margin-left:10.6%;">
<p>
<label>작성일 : </label>
#Html.DisplayTextFor(m => m.Article.ModifyDate)
</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
<label style="font-size:x-large;">문의내용</label>
<br />
<br />
#Html.DisplayTextFor(m => m.Article.Contents)
<br />
<br />
<br />
<br />
</p>
</div>
</div>
<div class="dividewhite2"></div>
<p>
#if (User.Identity.IsAuthenticated == true)
{
<button type="button" class="btn btn-sm btn-lgr-str" onclick="btnEdit()">수정하기</button>
<button type="button" class="btn btn-sm btn-lgr-str" onclick="btnReply()">답글달기</button>
}
<button type="button" class="btn btn-sm btn-lgr-str" onclick="javascript:history.go(-1);">목록이동</button>
<br />
<br />
<br />
<br />
</p>
<div>
#Html.Partial("_Comment", new ViewDataDictionary { { "id", Model.Article.ArticleIDX } })
#Html.Partial("_CommentView", new ViewDataDictionary { { "CommentIDX", ViewBag.CommentIDX }, { "idx", Model.Article.ArticleIDX } })
</div>
</div>
</div>
<div class="dividewhite8"></div>
</section>
</form>
<script >
function btnEdit() {
if (#User.Identity.Name.Equals(Model.Article.Members.ID).ToString().ToLower() == true)
{
location.replace("/Board/Edit?aidx=#Model.Article.ArticleIDX");
}
else
{
alert("권한이 없습니다.");
}
}
function btnReply() {
location.replace("ReplyCreate?aidx=#Model.Article.ArticleIDX");
}
[HttpGet]
public ActionResult ReplyCreate(int aidx)
{
Articles articleReply = new Articles();
return View(articleReply);
}
[HttpPost]
public ActionResult ReplyCreate(Articles replyArticles, int aidx)
{
try
{
replyArticles.Family = aidx;
replyArticles.ModifyDate = DateTime.Now;
replyArticles.ModifyMemberID = User.Identity.Name;
db.Articles.Add(replyArticles);
db.SaveChanges();
ViewBag.Result = "OK";
}
catch (Exception ex)
{
ViewBag.Result = "FAIL";
}
return View(replyArticles);
}
You have several problem in your HTML and JavaScript:
You're not submitting anything, you're redirecting the page in JavaScript.
You're hiding the button if the user is not authenticated, but everybody can see, copy, and run the URL from your JavaScript.
Even if you fix #1 and your ReplyCreate() action gets called, it's expecting 2 parameters, but you're only sending one (aidx). The other parameter (replyArticles) will be always null.
Your code is vulnerable to CSRF attack.
To fix #1, you can add the parameter to your form instead of JavaScript, and change your button's type to submit:
<form id="formdata"
action="#Url.Action("Detail", "Board", null, new { aidx = Model.Article.ArticleIDX })"
method="post" enctype="multipart/form-data">
<div class="dividewhite2"></div>
<p><button type="submit" class="btn btn-sm btn-lgr-str">답글달기</button></p>
</form>
Or you can use a hidden field.
To fix #2, move the check outside the form and delete your JavaScript:
#if (User.Identity.IsAuthenticated) {
<form id="formdata"
action="#Url.Action("Detail", "Board", null, new { aidx = Model.Article.ArticleIDX })"
method="post" enctype="multipart/form-data">
<div class="dividewhite2"></div>
<p><button type="submit" class="btn btn-sm btn-lgr-str">답글달기</button></p>
</form>
}
To fix #3, you'll have to add the replyArticles parameter to your form or as a hidden field.
To fix #4, you'll need to add the forgery check to your form and your action.
I´ve got a modal boostrap. I want to show the error of validation on boostrap modal. But when I leave the model empty and click on submit button Its just viewed as a standalone page.
Partial view:
#model WebApplication1.Models.Book
<form asp-controller="Home" asp-action="AddBook"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#frmaddbook">
<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="myModalLabel">Header of Modal</h4>
</div>
<div class="modal-body form-horizontal" id="frmaddbook ">
<span class="alert-danger">
#Html.ValidationSummary()
</span>
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-lg-3 col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="BookDescription" class="col-lg-3 col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookDescription" class="form-control" />
<span asp-validation-for="BookDescription" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
Index View :
<div class="panel panel-primary">
<div class="panel-body">
<div class="btn-group">
<a class="btn btn-primary marginbutoon" id="showBookgroup" data-toggle="modal" asp-action="AddBook"
data-target="#modal-book">
<i class="glyphicon glyphicon-plus"></i>
Add Book
</a>
</div>
</div>
i use this libraries at top of index view:
jquery.unobtrusive-ajax.min.js
jquery.validate.unobtrusive.min.js
and use at the bottom of index view:
<script src="~/js/book-index.js"></script>
book-index.js:
(function ($) {
function Home() {
var $this = this;
function initilizeModel() {
$("#modal-book").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new Home();
self.init();
})
}(jQuery))
Controller:
[HttpGet]
public IActionResult AddBook()
{
var b = new Book();
return PartialView("_AddBook", b);
}
[HttpPost]
[ValidateAntiForgeryToken]
//[HandleError]//not in core
public IActionResult AddBook(Book model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return PartialView("_AddBook", model);
}
Model :
public class Book
{
[Key]
public int BookId { get; set; }
[Display(Name = "Book Name :")]
[Required(ErrorMessage = "Enter Book Name Please ")]
public string BookName { get; set; }
[Display(Name = "Book Description")]
[Required(ErrorMessage = "Enter Book Description Please ")]
public string BookDescription { get; set; }
}
My code is shown above. How can i show validation error in modal partial view ?
You can set the Id of form as the data-ajax-update property value of the form , which is ajaxified. This value will be used as the jQuery selector when the result is received from the ajax call.
#model Book
<form asp-controller="Home" asp-action="AddBook" id="myform"
data-ajax="true" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#myform">
<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="myModalLabel">Add Book</h4>
</div>
<div class="modal-body form-horizontal" id="frmaddbook ">
<span class="alert-danger">
#Html.ValidationSummary()
</span>
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</form>
Now when you submit the form and model state validation fails, the action method code will return the partial view result with the validation error messages (generated by the validation helpers) and the jquery.unobtrusive-ajax.js library code will replace (because we specified that with data-ajax-mode="replace") the content of the result of the jquery selector #data-ajax-update (the form tag and it's inner contents) with the response coming back from the server.
Layout -> View -> Partial View
In the View:
<div class="col-md-8">
#{Html.RenderPartial("_komentari", commentlist);}
<div class="gap gap-small"></div>
<div class="box bg-gray">
<h3>#Res.commentwrite_title</h3>
#using (Ajax.BeginForm("postcomment", new { propertyid = Model.PublicID }, new AjaxOptions { UpdateTargetId = "commentsarea", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>#Res.commentwrite_content</label>
<textarea id="comment" name="comment" class="form-control" rows="6"></textarea>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value='#Res.commentwrite_btn' />
</div>
</div>
</div>
}
</div>
</div>
In the Partial View:
<div id="commentsarea">
<ul class="booking-item-reviews list">
#if (Model != null)
{
foreach (Comment item in Model)
{
<li>
<div class="row">
<div class="col-md-2">
<div class="booking-item-review-person">
<a class="booking-item-review-person-avatar round" href="#">
<img src="/assets/img/70x70.png" alt="Image Alternative text" title="Bubbles" />
</a>
<p class="booking-item-review-person-name">
#if (item.UserId != null)
{
<a href='#Url.Action("details", "user", new { userid = item.User.PublicId })'>#item.User.Username</a>
}
else
{
Anonymous
}
</p>
</div>
</div>
<div class="col-md-10">
<div class="booking-item-review-content">
<p>
#item.Content
</p>
<p class="text-small mt20">#item.DateOnMarket</p>
<p class="booking-item-review-rate">
#using (Ajax.BeginForm("reportcomment", new { comment = item.PublicId }, new AjaxOptions { UpdateTargetId = "reportscount", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<a id="submit_link" href="#">Spam?</a>
<a class="fa fa-thumbs-o-down box-icon-inline round" href="#"></a>
}
<b id="reportscount" class="text-color">#item.CommentReports.Count</b>
</p>
</div>
</div>
</div>
</li>
}
}
</ul>
</div>
<script>
$(function () {
$('a#submit_link').click(function () {
$(this).closest("form").submit();
});
});
</script>
View
Both scripts for Ajax are always included in the Layout (I'm already using Ajax on other pages too). On the View page, when I add a new comment, it is added in the database and shows the updated list of comments via ajax. Everything works fine.
Partial View
But if I want to report the comment as spam, I have to click on the link inside the Partial View (#submit_link), and after reporting, inside the #reportscount part, I want to show the updated number of reports of that comment. The actionresults returns that number like Content(numberofreports.toString()). It works but I get the number in a blank page?
Thank you very much.
It's better if you don't. The main issue is that, for security reasons, <script> tags are ignored, when HTML is inserted into the DOM. Since the Ajax.* family of helpers work by inserting <script> tags in place, when you return the partial via AJAX, those will not be present. It's better if you only include the HTML contents of the form in the partial, and not the form itself.