How to pass a dynamicy changed model to Partial view? - asp.net-core

I have a list of "workbooks" displayed in a table. Each workbook has a "Share" button next to the workbook's title. When the user clicks on the share button a modal dialog is shown containing a form.
The form allows the user to enter a list of the recipient's emails separated by a comma which is validated on the client-side.
As the dialog is located in a partial view _ShareView.cshtml that allows me to pass a modal WorkbookShareModel that has some fields like WorkbookId and Title. The goal here is to pass the details of each workbook when the user presses the share button (i.e. construct a modal and pass it to the already rendered model).
I am not sure how to pass a model to an already rendered view?
The solution have to be done on the client (i.e. dont involve actions on the server that return the partial view provided the parameters are passed). I want to avoid unnesessary calls to the server - we have all the data on the client regarding a workbook and I need to do a POST when the user types in list of emails.
This is my index.cshtml:
#section BodyFill
{
<div id="shareFormContainer">
#{ await Html.RenderPartialAsync("_ShareView", new WorkbookShareModel());}
</div>
<div class="landing-container">
<div class="workbook-container">
<table class="table">
<tbody>
#foreach (var workbook in Model.Workbooks)
{
string trClassName, linkText;
if (workbook.Metadata.SharedBy == null)
{
trClassName = "saved-workbooks";
linkText = workbook.Name;
} else {
trClassName = "shared-with-me";
linkText = string.Format(
BaseLanguage.SharedWithMeWorkbook,
workbook.Name,
workbook.Metadata.SharedBy,
workbook.Metadata.SharedDate.ToShortDateString()
);
}
<tr class="#trClassName">
<td>#Html.ActionLink(linkText, "Open", "OpenAnalytics", new { id = Model.Id, workbook = workbook.Name })</td>
<td class="last-modified-date" title="Last Modified Date">#workbook.ModifiedDate.ToShortDateString()</td>
<td class="share">
<button title="Share" class="share-button" onclick='showSharingView("#workbook.Name", "#workbook.Id", "#Model.Id")'> </button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
}
#section Scripts
{
<!--Load JQuery 'unobtrusive' validation -->
#await Html.PartialAsync("_ValidationScriptsPartial")
<script type="text/javascript">
// hide the modal as soon as the page loads
$('#shareFormModal').modal("hide");
function showSharingView(title, workbookId, id) {
$('#shareFormModal').modal("show");
// how to pass a WorkbookShareModel to my partial view from here?
}
function hideDialog() {
var form = $("#partialform");
// only hide the dialog if the form is valid
if (form.valid()) {
activateShareButtons();
$('#shareFormModal').modal("hide");
}
}
// Helper method that validates list of emails
function IsEmailValid(emailList, element, parameters) {
var SPLIT_REGEXP = /[,;\s]\s*/;
var EMAIL_REGEXP =
/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+##[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;
var emails = emailList.split(SPLIT_REGEXP);
for (var i = emails.length; i--;) {
if (!EMAIL_REGEXP.test(emails[i].trim())) {
return false;
}
}
return true;
}
</script>
}
That is my dialog:
#using DNAAnalysisCore.Resources
#model DNAAnalysisCore.Models.WorkbookShareModel
#* Partial view that contains the 'Share Workbook dialog' modal *#
<!-- Modal -->
<div onclick="activateShareButtons()" class="modal fade" id="shareFormModal" role="dialog">
<div class="modal-dialog modal-md">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Share Workbook - #Model.Title</h4>
</div>
#using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post, new { #id = "partialform" }))
{
<div class="modal-body">
<label>#BaseLanguage.Share_workbook_Instruction_text</label>
<div class="form-group">
<textarea class="form-control" asp-for="Emails" rows="4" cols="50" placeholder="#BaseLanguage.ShareDialogPlaceholder"></textarea>
<span asp-validation-for="Emails" class="text-danger"></span>
</div>
<input asp-for="Title" />
<input asp-for="Id" />
<input asp-for="WorkbookId"/>
</div>
<div class="modal-footer">
<button onclick="hideDialog()" type="submit" class="btn btn-primary">Share</button>
<button onclick="activateShareButtons()" id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
}
</div>
</div>
</div>

There are two solutions to solve your problem :
Option 1 :
Since you have got the parameters(title, workbookId, id) , you can call server side function using AJAX to render the partial view , then replace the DIV contained in the partial view with the updated contents in the callback function of AJAX .
You can click here for code sample .
Option 2 :
Directly update related input/area using Jquery . For example , the input tag helper :
<input asp-for="<Expression Name>">
generates the id and name HTML attributes for the expression name specified in the asp-for attribute. So you can set the value using Jquery like :
$("#Title").val("Title")
Please click here for Tag Helpers in forms in ASP.NET Core
With Option 2 , you need to clear the Emails area firstly after user click the share button ; With Option 1 , you don't need to care that since the HTML will replace entirely .

Related

Nothing happens when clicking search button on bootsrap and .net core

I am trying to learn .net core and what I want to do is: I have a search bar and a GetDetail function in controller. I want to trigger that function when clicking search button according to text in form. But when I click button, nothing happens. I did not complete the trigger part but even if I simply redirect to another page with href, also nothing happens. Here is my search bar view code which taken from sbadmin2:
<div class="row justify-content-center">
<div class="col-6 p-3">
<div class="input-group">
<input type="text" class="form-control bg-light border-0 small" placeholder="Input" aria-label="Search" aria-describedby="basic-addon2" id="code">
<button class="btn btn-primary" type="button" action="/Books/GetDetail?">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</div>
and the function I want to trigger is a get request:
public IActionResult GetDetail(string codes)
{
var request = $"?codes={codes}";
var products = _httpTool.HttpGetAsync<List<Products>>($"{AppSettings.ApiUrl}/GetProducts{request}");
var productList = products.Result.ToList();
return Json(productList);
}
Why nothing is happening and how can I achieve this?
Thanks in advance!
try something like this:-
<form method="post" asp-action="GetDetail">
//clarify code
<input type="submit" value="Search" class="btn btn-outline-primary mt-1"/>
//clarify code
</form>
[HttpPost]
public IActionResult GetDetail(string codes)
{
var request = $"?codes={codes}";
var products = _httpTool.HttpGetAsync<List<Products>>($"{AppSettings.ApiUrl}/GetProducts{request}");
var productList = products.Result.ToList();
return Json(productList);
}
After clicking Searchyou see something will happen.

Navigate to new view on button click in ASP.NET Core 3.1 MVC

I am trying to navigate the user to a new page with a button click. I am having issues with rendering the new view. Any time I do click on the button, I either get an error for a dropdown on my page, or I get the home page view but with my desired route in the URL. I wanted to note that the user will be navigating to this page from the home page, which I made into my new landing page on the app. I wanted to point that out in case something I did here can be modified.
How I created a new landing page
I want to navigate from my landing page to my book inventory page.
My View (On the landing page):
<form method="post" asp-controller="Home" asp-action="Home" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="#(new SelectList(ViewBag.message, "ID", "bookName"))">
</select>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
<div class="row">
<div class="form-group">
<a asp-controller="BookInventory" asp-action="Index">
<input type="button" value="Book Inventory Page" />
</a>
</div>
</div>
My Controller (On my landing page)
public void GetBooksDDL()
{
List<BookModel> bookName = new List<BookModel>();
bookName = (from b in _context.BookModel select b).ToList();
bookName.Insert(0, new BookModel { ID = 0, bookName = "" });
ViewBag.message = bookName;
}
[HttpGet("[action]")]
[Route("/Home")]
public IActionResult Home()
{
GetBooksDDL()
return View();
}
My Controller (On my book inventory page):
[HttpGet("[action]")]
[Route("/Index")]
public IActionResult Index()
{
return View();
}
I wanted to note that my breakpoint on my book inventory controller does hit the 'return View()', but it will still render the items from the homepage.
The error I get with the book dropdown says:
ArgumentNullException: Value cannot be null. (Parameter 'items')
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField).
I'm wondering why I'm getting this error when I'm trying to navigate to a different page. Since this is the new landing page, is it possible that it is passing along all of its data to the rest of the pages?
ArgumentNullException: Value cannot be null. (Parameter 'items')
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.ctor(IEnumerable
items, string dataValueField, string dataTextField, IEnumerable
selectedValues, string dataGroupField).
About this error, it means that you didn't set the value for the select element, before return to the view, please check the ViewBag.message value, make sure it contains value.
Note: Please remember to check the post method, if the Http Get and Post method returns the same page, make sure you set the ViewBag.message value in both of the action methods.
I wanted to note that my breakpoint on my book inventory controller
does hit the 'return View()', but it will still render the items from
the homepage.
In the BookInventory Controller Index action method, right click and click the "Go to View" option, make sure you have added the Index view.
Based on your code, I have created a sample using the following code, it seems that everything works well.
Code in the Home Controller:
[HttpGet("[action]")]
[Route("/Home")]
public IActionResult Home()
{
GetBooksDDL();
return View();
}
[HttpPost("[action]")]
[Route("/Home")]
public IActionResult Home(BookModel book, string bookName)
{
GetBooksDDL();
//used to set the default selected value, based on the book id (bookName) to find the book.
List<BookModel> booklist = (List<BookModel>)ViewBag.message;
book = booklist.Find(c => c.ID == Convert.ToInt32(bookName));
return View(book);
}
Code in the Home view:
#model BookModel
#{
ViewData["Title"] = "Home";
}
<h1>Home</h1>
<form method="post" asp-controller="Home" asp-action="Home" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="#(new SelectList(ViewBag.message, "ID", "bookName", Model == null? 0:Model.ID))">
</select>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
<div class="row">
<div class="form-group">
<a asp-controller="BookInventory" asp-action="Index">
<input type="button" value="Book Inventory Page" />
</a>
</div>
</div>
Code in the BookInventory controller:
public class BookInventoryController : Controller
{
[HttpGet("[action]")]
[Route("/Index")]
// GET: BookInventory
public ActionResult Index()
{
return View();
}
The screenshot as below:
If still not working, please check your routing configuration, perhaps there have some issue in the routing configure.
Your anchor tag formation is incorrect. You cannot write a button within anchor tag.
Do something like this:
<a asp-action="Index" asp-controller="BookInventory" class="btn btn-primary">Book Inventory Page</a>
Here the class will help your anchor tag look like buttons. I hope you have used bootstrap in your project. If not, then use it.
Hope this helps.
Here is another simple way:
<button type="button" class="btn" onclick="window.location.href = '/YourPage'">Button Title</button>

Why is asp-route passing on post value "0"

In my razor page in form I have button that on submit calls method "OnPostEditMe" with parameter "int id":
#{
var idbook = #Html.DisplayFor(a => a.EditBook.Id);
//idbook on page load gets id number of object EditBook when page loads, this works, if I add this value anywhere in razor page it displays correctly
}
<form method="post">
<div class="form-group row">
<div class="col-3 offset-3">
<button asp-page-handler="EditMe" asp-route-id="#idbook" type="submit">
Update #idbook
</button>
</div>
</div>
</form>
But when I click on this button, It calls method OnPostEditMe, but with parameter "0" instead value that was load with "idbook":
public async Task<IActionResult> OnPostEditMe(int id)
{
var tmp = id; //id is always 0
...
}
What is wrong, Why does asp-route-id="#idbook" not passing parameter that was load on page?
You have to set on the form instead of the button
<form method="post" asp-route-id="#idbook">
Or you can use hidden input
<input value="#idbook" name="id" id="id" type="hidden"/>.

HtmlBeginCollectionItem Get Current Item

I need:
Acess /Client/Create
Add dynamically Partial Views (/Product/Card) and bind them to Client.Products
In each Partial View when i click in a button open a bootstrap modal windows where i can set Product's information
Close the modal and reflect changes of modal reflect in the Card's Product.
The problem is: how to change product informations in another view(other than Card) and reflect to the product of the card?
#using (Html.BeginCollectionItem("Products"))
{
#Html.HiddenFor(model => model.ClientID)
#Html.HiddenFor(model => model.ProductID)
<div class="card">
<img class="card-img-top" src="http://macbook.nl/wp-content/themes/macbook/images/png/iphone318x180.png" alt="Grupo Logo">
<div class="card-block">
<h4 class="card-title">#Model.Name</h4>
<p class="card-text">#Model.Desc</p>
<div class="btn-group">
<button type ="button" class="btn btn-primary open-modal" data-path="/Product/Edit/#Model.ProductID">Edit</button>
<button type="button" class="btn btn-primary open-modal" data-path="/Product/Features/#Model.ProductID">Features</button>
</div>
</div>
</div>
}
You can do this is another view (or by dynamically loading another view into a modal. The object has not been created yet, and since you using BeginCollectionItem() to generate new items, any other view you used would not be using the same Guid created by that helper so you would not be able to match up the collection items.
Instead, include the 'other' properties within the partial, but put them in a hidden element that gets displayed as a modal when you click the buttons.
The basic structure of the partial for adding/editing a Product would be
<div class="product">
#using (Html.BeginCollectionItem("Products"))
{
#Html.HiddenFor(m => m.ClientID)
#Html.HiddenFor(m => m.ProductID)
<div class="card">
....
<button type ="button" class="btn btn-primary edit">Edit</button>
</div>
// Modal for editing additional data
<div class="modal">
#Html.TxtBoxFor(m => m.SomeProperty)
#Html.TxtBoxFor(m => m.AnotherProperty)
....
</div>
}
</div>
And then handle the buttons .click() event (using delegation since the partials will be dynamically added to the view) to display the associated modal (assumes you have a <div id="products"> element that is the container for all Products)
$('#products').on('click', '.edit', function() {
var modal = $(this).closest('.product').find('.modal');
modal.show(); // display the modal
});

what is the use of insert mode on AJAXFORM in MVC?

When i am clicking the ajax from is loaded the partila view correctly inside the div have id as mytraget. But my question is what is the use of insertmode in ajax form.
On submitting the ajax form it always load the partial view inside of the div have id as mytraget on all type of insert mode. Then what is the of insert mode?
My original view named as MyView
#model Example.Models.mytest
<div id="mytraget"> </div>
#using(Ajax.BeginForm("myParialAjax", new AjaxOptions() { InsertionMode = InsertionMode.InsertBefore, UpdateTargetId = "mytraget" }))
{
<p>Name</p> #Html.TextBoxFor(m => m.string1)
<input type="submit" value="Submit" />
}
My Cobtroller Method
[HttpPost]
public PartialViewResult myParialAjax(mytest s)
{
return PartialView("Mypartial", s);
}
My Parial view which is named as Mypartial
#model Example.Models.mytest
<p>
#Html.TextBoxFor(m =>m.string1)
</p>
In all type of insert mode i get partial view inside of the the below div.
Output :
<div id="mytraget">
<p>
<input id="string1" type="text" value="asdf" name="string1">
</p>
</div>
I got myself the answer What i am missing is Need to insert some tags inside of the target tag.
Like below:
#model Example.Models.mytest
<div id="mytarget">
<p> my para </p>
</div>
#using(Ajax.BeginForm("myParialAjax", new AjaxOptions() { InsertionMode = InsertionMode.InsertBefore, UpdateTargetId = "mytarget" }))
{
<p>Name</p> #Html.TextBoxFor(m => m.string1)
<input type="submit" value="Submit" />
}
Now here InsertionMode.InsertBefore will insert my partial view above the paragraph tag and InsertionMode.InsertAfter will insert my partial view after the paragraph tag and InsertionMode.Replace will replace the whole things which is inside of the tag with my target id.