.net-core Site with Partial Vue.js Frontend Form Fields - vuejs2

I am trying to create a site that has partial implementation of Vue.js, I am looking at using Vue.js as from what I understand it does not require a SPA site like other JS frameworks and I believe this framework ticks the boxes required.
I have a basic form that I want to be used to Create, Update and Delete objects.
The data is received via a SAL which calls an API, all Create, Update and Delete calls will go through the same API.
I have been able to do a HttpGet and HttpPost to Get and Update the data and show it on a simple form.
However when I try to display just a blank form I get the following errors:
Error Received
The code I have is as followed:
.cshtml page
#model bms.accessbookings.com.Types.ViewModels.ShowVenueViewModel
#{
ViewData["Title"] = "Venue";
}
<div class="m-grid__item m-grid__item--fluid m-wrapper">
<div class="m-content">
<div class="row">
<div id="venueForm">
Venue ID: <input type="text" v-model="venue.venueId" />
<br/>
Venue Name: <input type="text" v-model="venue.venueName" />
<br/>
Address: <input type="text" v-
model="venue.address.addressLine1"/>
<br/>
Line 2: <input type="text" v-
model="venue.address.addressLine2"/>
<br/>
City: <input type="text" v-model="venue.address.city"/>
<button type="button" v-on:click="sendToServer"
style="padding: 0; border: none; background: none;
cursor: pointer;">
<i class="la la-save"></i>
</button>
</div>
</div>
</div>
</div>
#section Scripts {
<script src="/js/venueform.js" type="text/javascript"></script>
}
.cs ViewModel:
public class ShowVenueViewModel
{
public int VenueId { get; set; }
public string VenueName { get; set; }
public Address Address { get; set; }
}
Address element contains Line1, Line2, City etc
VenueController Get and Post:
[HttpGet]
[Route("GetVenue")]
public ShowVenueViewModel GetVenue(int venueId = 0)
{
ShowVenueViewModel viewModel = new ShowVenueViewModel
{
Address = new Address()
};
if (venueId > 0)
{
viewModel = _venueImplementation.GetShowVenueViewModel(venueId);
}
return viewModel;
}
[HttpPost]
[Route("SaveVenue")]
public ShowVenueViewModel SaveVenue([FromBody]ShowVenueViewModel venueViewModel)
{
return venueViewModel;
}
.js page:
$(document).ready(function() {
var venueId = window.location.pathname.substring(7);
const vm = new Vue({
el: '#venueForm',
data () {
return {
venue: {}
}
},
props: {
currentevent: Object
},
created() {
Object.assign(this.venue, this.currentevent || {});
},
mounted: function() {
axios.get('/venue/GetVenue', { params: { venueId: venueId } }).then(response => {
this.venue = response.data;
});
},
methods: {
sendToServer: function () {
var self = this;
console.log("Venue getting updated");
axios.post('/venue/SaveVenue', self.venue)
.then(response => {
this.venue = response.data;
console.log("Venue Updated");
});
}
}
});
});
At the moment if the venue has items it returns these items without a problem and displays them into the form, I can edit the inputs and "save" them which then returns the newly saved information (save functionality not yet connected to my BLL / SAL).
However when no Venue object is returned (empty) the form does not display at all, and so there is no way to enter details onto a blank form to "save" and create a new venue.
Still really new to vue.js and I find it hard to find guides that are not pointing to CLI or SPA style sites.
I may have a lot of things wrong here, but if there are any pointers to help me I would be very grateful.

Ok well the error you're getting comes from your template (.cshtml page). You need either to make sure venue.address always has a value, or, safer, test for the presence of venue.address.addressLine1 before displaying it.
When you get an error in a render function, vue can't tell you the line number. But you know it's in the template somewhere and it's generally not hard to find. Keep your templates short :-) (the one shown is fine).

Related

How to return a partial view and invoke the model's constructor with DI system

I have a parent view, and want to call a handler with ajax that will return a partial view. The problem I'm having is that my partial view needs it's model also which has all its own OnGet, OnPost etc methods.
When calling:
public PartialViewResult OnGetPartialView(Guid Id)
{
return Partial("MyPartialView");
}
I don't know how to add the model for this view, as its only constructor takes several services that usually the DI systems takes care of for me. I also need to pass the Id to the partial view as its used in the OnGet method (which I'm assuming will be invoked when this works properly).
Thanks!
To pass the model to the partial view in razor pages, you need to add the second parameter as the model you need to pass when returning to the Partial:
return Partial("MyPartialView", model);
It should be noted that in MyPartialView, you need to delete the #Page in the first line of the page and add the model reference you passed.
This will ensure that MyPartialView receives the model data, otherwise there will be an error that model is null.
Regarding the OnGet and OnPost methods of the MyPartialView page you mentioned, if you delete #Page, they will lose their actual contact meaning.
My suggestion is that if you have some post or get methods that need to be used in MyPartialView, you can write these methods to other pages.
Here is a complete example:
TestModel.cshtml.cs:
public class TestModel : PageModel
{
public void OnGet()
{
}
public PartialViewResult OnGetPartialView(Guid Id)
{
List<Person> persons = new List<Person>()
{
new Person(){ Age = 12,
FirstName = "dd",
LastName = "aa" },
new Person(){ Age = 13,
FirstName = "bb",
LastName = "ff" },
new Person(){ Age = 14,
FirstName = "ggr",
LastName = "rwe" },
};
return Partial("MyPartialView", persons);
}
public IActionResult OnPostTest()
{
return Content("aa");
}
}
TestModel.cshtml:
#page
#model WebApplication_razorpage_new.Pages.TestModel
#{
ViewData["Title"] = "Test";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>Test</h1>
<input id="Button1" type="button" value="Get partial view" /><br /><br /><br />
<div id="partial" class="border"></div>
#section Scripts{
<script>
$(function () {
$("#Button1").click(function () {
$.ajax({
type: "get",
url: "/Test?handler=PartialView",
data: { Id: "780cd7ce-91b2-40fd-b4c8-7efa6b7c84a5" },
success: function (data) {
$("#partial").html(data);
}
});
});
})
</script>
}
MyPartialView.cshtml:
#model List<Person>
<form method="post">
<input id="Button1" type="button" value="button" onclick="Click()" />
<input id="Text1" type="text" />
<table class="table table-bordered">
#foreach (var item in Model)
{
<tr>
<td>#item.Age</td>
<td>#item.FirstName</td>
<td>#item.LastName</td>
</tr>
}
</table>
</form>
<script>
function Click() {
$.ajax({
type: "POST",
url: "/Test?handler=test",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#Text1").val(data);
}
});
}
</script>
Here is the test result:

How to dynamically add an item to a list within a list in a ViewModel using Razor and .NET Core 2.2?

I've been following this tutorial (i did it in asp.net core 2.2):
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ on how to edit a variable lenght list in asp.net. In this tutorial, we're just handling a list of gifts. I'm trying to apply this method to a more complex model.
I have an object called Workout.cs who contains a List of Section.cs. The Section.cs object contains a List of Movement.cs
public class Workout
{
public string Name { get; set; }
public IEnumerable<Section> Sections { get; set; } = new List<Section>();
}
public class Section
{
public int NbRounds { get; set; }
public string Name { get; set; }
public IEnumerable<Movement> Movements { get; set; } = new List<Movement>();
}
public class Movement
{
public string Name { get; set; }
}
WorkoutController
public IActionResult BlankSection()
{
return PartialView("_SectionEditor", new Section());
}
public IActionResult BlankMovement()
{
return PartialView("_MovementEditor", new Movement());
}
Index.cshtml
#model Workout
<h2>Workout</h2>
<form asp-action="Index" method="post" asp-controller="Workout">
<div id="editorRows">
#foreach (var item in Model.Sections)
{
<partial name="_SectionEditor" model="item" />
}
</div>
<a id="addItem" asp-action="BlankSection" asp-controller="Workout">Add Section...</a> <br />
<input type="submit" value="Finished" />
</form>
#section scripts {
<script>
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
</script>
}
_SectionEditor.cshtml
#model Section
#{
Layout = "~/Views/Shared/_LayoutEditor.cshtml";
}
<div class="editorRow">
#using (Html.BeginCollectionItem("sections"))
{
<span>Name: </span> #Html.EditorFor(m => m.Name);
<span>Rounds: </span>#Html.EditorFor(m => m.NbRounds, new { size = 4 });
}
delete
<div id="editorMovement">
#foreach (var item in Model.Movements)
{
<partial name="_MovementEditor" model="item" />
}
</div>
<a id="addMovement" asp-action="BlankMovement" asp-controller="Workout">Add Movement...</a> <br />
</div>
#section Scripts {
<script>
$(document).ready(function () {
$("a.deleteRow").on("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
});
$("#addMovement").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorMovement").append(html); }
});
return false;
});
</script>
}
MovementEditor.cshtml
#model Movement
#{
Layout = "~/Views/Shared/_LayoutEditor.cshtml";
}
<div class="editorMovement">
#using (Html.BeginCollectionItem("movements"))
{
<span>Name: </span> #Html.TextBoxFor(m => m.Name);
}
delete
</div>
#section Scripts {
<script>
$(document).ready(function () {
$("a.deleteMovement").on("click", function () {
$(this).parents("div.editorMovement:first").remove();
return false;
});
});
</script>
}
With the tutorial, it's working fine when I'm adding sections to my workout, but when I'm trying the same to add movements to my sections, it's not working anymore. I would like to be able to add as many sections as I want to my workout, and for each section, as many movements as I want, and send it to the controller. How could I do that ?
thanks a lot
First: MovementEditor appears to be a partial in the controller, but not in the view file (despite the '_').
Second: since _SectionEditor is a partial view, you can't define #section scripts in it, because it's already defined in the main view Index. To solve this issue, you need to put all the scripts in the main view Index.
P.S: don't forget to change jquery selectors for items in the partial views, i.e: $("#addMovement") will not point to the anchor tag because it was not there when the DOM tree was created. Instead write $("body #addMovement") and it will get the anchor tag.

Vue File Upload with Parameters

Hi Guys i create a component to upload files and its working so far, but along with the data I'll like to pass some parameters too, for example
HTML
<div class="col-md-4">
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>
Files
v-on:click="upload()">Submit</v-btn>
</div>
</div>
</div>
Script
import
axios.post('/api/upload', this.files)
.then(resuta);
}, error => {
console.error(error);
});
}
here (axios.post('/api/upload', this.files)) i would like to include
email: this.profile.email
Because I'm adding this parameter to the file name on my backend
Controller
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile(string email)
{
var files = Request.Form.Files;
foreach (var file in files)
{
}
}
}
return Ok();
}
Given this.files is a FormData instance, you should be able to set any field you want. For example
upload () {
this.files.set('email', this.profile.email)
axios.post('/api/upload', this.files)...
I don't know .NET MVC very well any more but this would add email as a form param in the request.
You can use this way;
HttpContext.Request.Form.Where(p => p.Key == "email").FirstOrDefault().Value;

Display mvc partial view with errors on parent page

I have a page with multiple forms, each as a partial. I want to post each partial on submit. If there are errors, I want the validation errors to show in the partial as part of the main page i.e. I don't want to just see the partial on it's own page if there are errors. Am I correct in saying this behavior is only possible with an ajax post? How would I return the model state errors WITHOUT an ajax post, just a normal form post?
Edit:
Still seeing the partial on it's own page
Partial -
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "LoginForm" }))
{
#Html.ValidationMessage("InvalidUserNamePassword")
<fieldset class="fieldset">
<div>
<label for="form-field-user_id">User ID</label>
<span>
#Html.TextBoxFor(x => x.Username, new { #class = "form-field__input form-field__input--text", #id = "form-field-user_id"})
</span>
</div>
</fieldset>
<div class="form-field__button">
<button id="loginButton" type="submit" class="button button--primary">Login</button>
</div>
}
<script>
$('#loginButton').click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("Login", "Account")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
$("#LoginForm").html(result);
}
},
error: function () {
$("#LoginForm").html(result);
}
});
});
</script>
Controller -
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
{
return PartialView("~/Views/Account/_Login.cshtml", model);
}
return Json(new { redirectTo = Url.Action("Index", "Profile") });
}
Yes, you are correct in saying this behavior is only possible with an ajax post.
There are a few problems with your current script meaning that you will not get the desired results.
Firstly your button is a submit button meaning that it will do a normal submit in addition to the ajax call unless you cancel the default event (by adding return false; as the last line of code in your script). However it would be easier to just change the button type to type="button"
<button id="loginButton" type="button" class="button button--primary">Login</button>
The ajax call will now update the existing page, however it will add the returned partial inside the existing <form> element resulting in nested forms which is invalid html and not supported. Change your html to wrap the main views form in another element
<div id="LoginFormContainer">
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "LoginForm" }))
{
....
<button id="loginButton" type="button" class="button button--primary">Login</button>
}
</div>
and then modify the script to update the html of the outer element
success: function (result) {
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
$("#LoginFormContainer").html(result); // modify
}
},
Finally, your rendering dynamic content so client side validation will not work for the returned form. Assuming your properties have validation attributes (for example the [Required] attribute on the Userame property), you need to reparse the validator after loading the content
var form = $('#LoginForm');
....
} else {
$("#LoginFormContainer").html(result);
// reparse validator
form.data('validator', null);
$.validator.unobtrusive.parse(form);
}
You noted that you have multiple forms on the page, in which case your ajax options should be
data: $('#LoginForm').serialize(),
or if your declare var form = $('#LoginForm'); as per the above snippet, then data: form.serialize(), to ensure you are serializing the correct form.
Side note: There is no real need to change the id attribute of the textbox (it will be id=Username" by default and you can simply use
#Html.LabelFor(x => x.UserName, "User ID")
#Html.TextBoxFor(x => x.Username, new { #class = "form-field__input form-field__input--text" })
or just #Html.LabelFor(x => x.UserName) of the property is decorated with [Display(Name = "User ID")]

Creating dynamic view from a controller in MVC

I have this controller and view:
public ActionResult DynamicView()
{
return View();
}
_
#model ChatProj.Models.GroupNumber
#{
ViewBag.Title = "DynamicView";
}
<h2>DynamicView</h2>
<fieldset>
<legend>Create a room</legend>
<div class="editor-label">
#Html.LabelFor(model => model.GroupId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.GroupId)
#Html.ValidationMessageFor(model => model.GroupId)
</div>
<input type="submit" value="DynamicView" />
</fieldset>
This is what it looks like on the page.
That's fine and dandy, but I would like to pass that number to a controller, which then passes it to a view. I would like to pass it to this view:
#using PagedList.Mvc;
#using ChatProj.App_Code;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Grupprum 1";
}
<h2>Grupprum 1</h2>
<style>
ul {list-style-type:circle;}
</style>
<div class="container">
<div class="nano chat">
<div class="content">
<ul id="discussion">
</ul>
</div>
</div>
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" disabled="disabled" />
<input type="hidden" id="displayname" />
</div>
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
<script src="~/Scripts/jquery.nanoscroller.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
$(".nano").nanoScroller();
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
$(document).ready(function () {
$("#sendmessage").removeAttr("disabled");
$('#message').keypress(function (e) {
if (e.keyCode == 13)
$('#sendmessage').click();
});
});
// Get the user name and store it to prepend to messages.
// Set initial focus to message input box.
$('#message').focus();
$.connection.hub.qs = { "room": "Grupprum 1" };
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
Specifically I would want it at $.connection.hub.qs = { "room": "Grupprum 1" }; to replace the 1.
So I've created these controllers which are faulty and incomplete:
[HttpPost]
public ActionResult DynamicView(int? roomNumber)
{
return View(GroupRoom(roomNumber));
}
public ActionResult GroupRoom(int roomNumber)
{
return View();
}
Does anyone know how I should change my controllers and views so that I'm able to insert a number in my DynamicGroup view, and get a view back based on the inserted number and the lastly mentioned view?
You could pass the number from the model to the new action just how #Matt Bodily did. But if you want to use a different model on your new view, you can use the below code instead:
public ActionResult GroupRoom(int roomNumber)
{
ViewBag.RoomNumber = roomNumber;
return View();
}
This way, you can use a different model for this page, if you want to. To display this ViewBag on the page, use this code anywhere you want:
#ViewBag.RoomNumber
I hope that helps you out.
How you have it set up the Model.GroupID will be set on the first view so change your controller like this
[HttpPost]
public ActionResult DynamicView(GroupNumber model)
{
//model.GroupId here will be what was selected on the first view
return RedirectToAction("GroupRoom", "Controller", new { GroupId = model.GroupId });
}
public ActionResult GroupRoom(int GroupId)
{
var model = //build your model based on the selected GroupId
return View(model);
}