PartialView is opening in another page - .net-core

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?

Related

How do I stop my button from failing with input in the box?

I have a button that is taking text entry in an input box and appending to a URL and redirecting.
The entire system is working, however the problem I am facing is when I enter the text and click the button nothing happens. Every time I add text, the button does nothing.
When I dont enter any information, the button takes me to the url that should have the input appended to (wihtout the appended information)
<div class="pen-title">
<div class="container">
<div class="card"></div>
<div class="card">
<form>
<div class="input-container">
<input type="#{type}" id="txt" required="required"/>
<label for="#{label}">Password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button id="btn"><span>Go</span></button>
</div>
</form>
</div>
</div>
</div>
the JS:
<script>
var nickname = document.getElementById("txt");
function redirect () {
window.location.href = "https://theurl.com/details?info=" + nickname.value;
};
document.getElementById("btn").addEventListener('click', redirect);
</script>
If I use the JS with the following button settings:
(THE FOLLOWING CODE WORKS AND IS ONLY A DEMO TO SHOW THAT THE FUNCTION IS ACTUALLY WORKING FULLY)
The code with the bug is the code above this line.
<div class ="input"> <input type="text" id="txt" />
<label for="txt"> Enter Reg </label> </div>
<div class="buttons">
<button class="pulse" id="btn">Pulse</button>
</div>
<script>
var nickname = document.getElementById("txt");
function redirect () {
window.location.href = "https://carservicesinreading.co.uk/check-mot-history/details?car-reg=" + nickname.value;
};
document.getElementById("btn").addEventListener('click', redirect);
</script>
it works first time. However the template of this set up was different css for the input box and different CSS for the button and I just cannot get it in the layout I would like.
Thank you for any help!
the only thing i can see as you haven't provided much info. on the button i added type submit.see if i helps as i can see it redirects and says cannot find mot details.do you have real reg no for testing?
update:removed form tags.
var nickname = document.getElementById("txt");
function redirect() {
window.location.href = "https://theurl.com/details?info=" + nickname.value;
};
document.getElementById("btn").addEventListener('click', redirect);
<div class="pen-title">
<div class="container">
<div class="card"></div>
<div class="card">
<div class="input-container">
<input type="#{type}" id="txt" required="required" />
<label for="#{label}">Password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button id="btn"><span>Go</span></button>
</div>
</div>
</div>
</div>

Pass input with route id to controller method together

I want to create input with game amount. User will write how many copy of concrete game wants to buy. Then two parameters will pass to AddToCart method. First will be gameId like below (it works well) and user amount input. How to pass these two values together into controller method?
View:
#model IEnumerable
<link rel="stylesheet" href="~/css/productcards.css">
<div class="container">
<div class="row">
#foreach (var game in Model)
{
<div class="col-md-3">
<div class="product-grid">
<div class="product-image">
<a asp-controller="Game" asp-action="ShowDetails" asp-route-productId=#game.GameId>
<img class="pic-1" src="~/images/#game.ImagePath">
</a>
</div>
<div class="product-content">
<h3 class="title">
<a asp-controller="Game" asp-action="ShowDetails" asp-route-productId=#game.GameId>#game.Title</a>
</h3>
<div class="price">#game.Price.ToString() zł</div>
<a asp-controller="Cart" asp-action="AddToCart" asp-route-gameId="#game.GameId" class="btn btn-primary"><i class="fa fa-cart-plus"></i> KUP</a>
</div>
</div>
</div>
}
</div>
</div>
Controller:
public RedirectToActionResult AddToCart(int gameId)
{
var selectedGame = _appDbContext.Games.FirstOrDefault(x => x.GameId == gameId);
if(selectedGame != null)
{
_cart.AddToCart(selectedGame, 1);
}
return RedirectToAction("Index");
}
Change your view like below:
#foreach (var game in Model)
{
<form method="post">
<div class="col-md-3">
<div class="product-grid">
<div class="product-content">
<h3 class="title">
<a asp-controller="Game" asp-action="ShowDetails" asp-route-productId=#game.GameId>#game.Title</a>
</h3>
<div class="price">#game.Price.ToString() zł</div>
<div class="amount"><input name="amount" type="number" /></div> #*add this line*#
</div>
</div>
</div>
<div class="col-md-3">
#*change <a> to <input> and add a <form>*#
<input type="submit" asp-route-gameId="#game.GameId" asp-controller="Cart" asp-action="AddToCart" class="btn btn-primary" value="KUP"/>
</div>
</form>
}
Action:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddToCart(int gameId,int amount)
{
//do your stuff...
}
Result:

How to import parameters from post method

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.

ASP.NET MVC is it possible to use ajax.beginform inside a partial view?

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.

Post back Method not get call on button click in MVC4

i have created a login page without _layout.cshtml in mvc4 and added two text box with a button. But when i click button it no getting post back. I have tried using breakpoint. pls help. My Code
#model MapProjectMVC.Models.LoginModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Special Spots</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="loginBox">
<div class="loginHead">
<img src="img/logo.png" alt="Special Spots - responsive admin panel" title="Special Spots - responsive admin panel" />
</div>
<div class="control-group">
<label for="inputEmail">
User Name</label>
#Html.TextBoxFor(a => a.UserName)
</div>
<div class="control-group">
<label for="inputPassword">
Password</label>
#Html.TextBoxFor(a => a.Password)
</div>
<div class="control-group" style="margin-bottom: 5px;">
</div>
<div class="form-actions">
<button type="submit" class="btn btn-block">
Sign in</button>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
</body>
</html>
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel LM)
{
var UserId = new ObjectParameter("userId",typeof(string));
var res = new ObjectParameter("res",typeof(Int32));
int i = ssc.ValidateAdminLogin(LM.UserName, LM.Password, UserId, res);
if (Convert.ToInt32(res) == 1)
{
}
else
{
ModelState.AddModelError("", "Login details are wrong.");
}
return View(LM);
}
You have to put the input elements and submit button in form. For this purpose you can use asp.net mvc Html Helper Extension for form Html.BeginForm() this way:
#using(Html.BeginForm())
{
<div class="loginBox">
<div class="loginHead">
<img src="img/logo.png" alt="Special Spots - responsive admin panel" title="Special Spots - responsive admin panel" />
</div>
<div class="control-group">
<label for="inputEmail">
User Name</label>
#Html.TextBoxFor(a => a.UserName)
</div>
<div class="control-group">
<label for="inputPassword">
Password</label>
#Html.TextBoxFor(a => a.Password)
</div>
<div class="control-group" style="margin-bottom: 5px;">
</div>
<div class="form-actions">
<button type="submit" class="btn btn-block">
Sign in</button>
</div>
</div>
}
There are many overloads of Html.BeginForm(), See all overloads here

Resources