Couldn't Add two numbers and get the Total using Asp.net MVC - asp.net-mvc

I am trying to do a simple calculator program in asp.net MVC. I like to add two number and get the total. But I couldn't do the task. I am a beginner at asp.net MVC. code which I tried so far I attached below.
Model
namespace WebApplication30.Models
{
public class cal
{
public int no1 { get; set; }
public int no2 { get; set; }
public int tot { get; set; }
}
}
Controller
public class CalController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(cal c)
{
c.tot = c.no1 + c.no2;
return View(c);
}
}
** This is a View pass the values from the controller**
#model WebApplication30.Models.cal
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="row">
#using (Html.BeginForm("Index", "cal", FormMethod.Post))
{
<div class="form-group">
<label for="no">No 1</label>
<input type="text" class="form-control" id="no1" name="no1">
</div>
<div class="form-group">
<label for="pwd">No 2</label>
<input type="text" class="form-control" id="no2" name="no2">
</div>
<div class="form-group">
<label for="pwd">total</label>
<input type="text" class="form-control" id="tot" name="tot">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
</div>
enter image description here

You need to bind the input value to the cal Model. Also, need to add cal model when get index action called .
CONTROLLER
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using WebApplication30.Models;
namespace WebApplication30
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new cal());
}
[HttpPost]
public ActionResult Index(cal c)
{
c.tot = c.no1 + c.no2;
return View(c);
}
}
}
VIEW
#model WebApplication30.Models.cal
#{
ViewBag.Title = "Index";
}
<body>
<h2>Index</h2>
<div class="row">
#using (Html.BeginForm("/Index", "Home", FormMethod.Post))
{
<div class="form-group">
<label for="no">No 1</label>
<input type="text" class="form-control" id="no1" name="no1" value="#Model.no1">
</div>
<div class="form-group">
<label for="pwd">No 2</label>
<input type="text" class="form-control" id="no2" name="no2" value="#Model.no2">
</div>
<div class="form-group">
<label for="pwd">total</label>
<input type="text" class="form-control" id="tot" name="tot" value="#Model.tot">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
</div>
</body>
NOTE: add / before Index while submitting the form it creates sometimes a problem.
DEMO

Related

validation error duplication in both forms

I've got two partial views, each contains a form. When i submit either of them, validation error appears as a duplicate in both partials. What am I missing, or probably have a double of.
I had to move each form in a separate partial view in order to give each of them its own Model.
My main view:
#inject Microsoft.Extensions.Localization.IStringLocalizer Localizer
#model LoginRegisterViewModel
#{
Layout = "_Layout_";
}
#if (Model.LoginViewModel.EnableLocalLogin)
{
<div class="loginRegister">
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header loginpage">
<main class="fullHeight">
<div class="flexValign" id="overview">
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--8dp roundedWrapper">
#Html.Partial("_LoginPartial", Model.LoginViewModel)
#Html.Partial("_RegisterPartial", Model.RegisterViewModel)
</section>
</div>
</main>
</div>
</div>
}
my partials:
#inject Microsoft.Extensions.Localization.IStringLocalizer Localizer
#model RegisterViewModel
<div class="mdl-card mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--4-col-phone darkBckrnd">
#using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
<div class="fixedHeight mdl-grid mdl-card__supporting-text mdl-typography--text-center mdl-color-text--white">
<div class="innerWrapper">
#await Html.PartialAsync("_InputValidation")
<input type="hidden" asp-for="RegisterReturnUrl" />
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input type="password" class="mdl-textfield__input" asp-for="NewPassword" autocomplete="new-password">
<label class="mdl-textfield__label mdl-color-text--white" for="Password">#Localizer["password"]
&ast;</label>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input type="password" autocomplete="off" class="mdl-textfield__input" asp-for="NewPasswordAgain">
<label class="mdl-textfield__label mdl-color-text--white"
for="PasswordAgain">#Localizer["repeatPassword"]
&ast;</label>
</div>
</div>
</div>
<div class="btnContainer">
<button type="submit" value="register" name="button"
class="general mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored mdl-color--cyan-500 mdl-shadow--8dp"
id="RegisterButton">#Localizer["createAccount"]</button>
</div>
}
the other partial:
#inject Microsoft.Extensions.Localization.IStringLocalizer Localizer
#model LoginViewModel
<div class="mdl-card mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--4-col-phone white">
#using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div
class="fixedHeight mdl-grid mdl-card__supporting-text mdl-typography--text-center mdl-color-text--blue-grey-900">
<div class="innerWrapper">
<partial name="_InputValidation" />
<input type="hidden" asp-for="ReturnUrl" />
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" asp-for="Username">
<label class="mdl-textfield__label mdl-color-text--blue-grey-600"
for="Username">#Localizer["userNameOrEmail"]</label>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input type="password" class="mdl-textfield__input" asp-for="Password" autocomplete="off">
<label class="mdl-textfield__label mdl-color-text--blue-grey-600"
for="Password">#Localizer["password"]</label>
</div>
</div>
</div>
<div class="btnContainer">
<button type="submit" value="login" name="button"
class="general mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored mdl-color--cyan-500">
#Localizer["login"]</button>
</div>
}
Models:
using System;
using System.Collections.Generic;
using System.Linq;
namespace IdentityServer4.Quickstart.UI
{
public class LoginViewModel : LoginInputModel
{
public bool AllowRememberLogin { get; set; } = true;
public bool EnableLocalLogin { get; set; } = true;
public string LoginPage { get; set; } = "Login";
public IEnumerable<ExternalProvider> ExternalProviders { get; set; } = Enumerable.Empty<ExternalProvider>();
public IEnumerable<ExternalProvider> VisibleExternalProviders => ExternalProviders.Where(x => !String.IsNullOrWhiteSpace(x.DisplayName));
public bool IsExternalLoginOnly => EnableLocalLogin == false && ExternalProviders?.Count() == 1;
public string ExternalLoginScheme => IsExternalLoginOnly ? ExternalProviders?.SingleOrDefault()?.AuthenticationScheme : null;
}
}
second model
using IdentityServer.DTOs;
using IdentityServer.Models;
namespace IdentityServer4.Quickstart.UI
{
public class RegisterViewModel
{
public string Email { get; set; }
public string NewPassword { get; set; }
public string NewPasswordAgain { get; set; }
public string RegisterReturnUrl { get; set; }
}
then two Models united. I have united these two models to cover them both in controller.
using System;
using System.Collections.Generic;
using System.Linq;
namespace IdentityServer4.Quickstart.UI
{
public class LoginRegisterViewModel
{
public LoginViewModel LoginViewModel { get; set; }
public RegisterViewModel RegisterViewModel { get; set; }
}
}
and controller:
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Username);
if (await _userManager.CheckPasswordAsync(user, model.Password))
{
var performAdditionalCheck = true;
// If the user has unknown provider let him pass
if (user.Provider == UserAuthentificationProvider.Unknown) performAdditionalCheck = false;
if (context != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);
if (client.Properties["forceAuthentification"] == "false") performAdditionalCheck = false;
}
if (performAdditionalCheck)
{
return await RedirectToAuth(model);
}
else
{
return await SignInUserWithModel(user, model);
}
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId: context?.ClientId));
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await BuildLoginRegisterViewModelAsync(model);
return View(vm.LoginViewModel.LoginPage, vm);
}
I've got two partial views, each contains a form. When i submit either of them, validation error appears as a duplicate in both partials.
You can refer to the following sample code snippet and this doc about "Client-side validation" to valid user inputs within multiple partial views.
Main View
#model LoginRegisterViewModel
#{
ViewData["Title"] = "LoginRegister";
}
<h1>LoginRegister</h1>
#await Html.PartialAsync("_LoginPartial", Model.LoginViewModel)
#await Html.PartialAsync("_RegisterPartial", Model.RegisterViewModel)
#section scripts{
<partial name="_ValidationScriptsPartial" />
}
_LoginPartial.cshtml
#model LoginViewModel
#using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Username" class="control-label"></label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="login" class="btn btn-primary" />
</div>
}
_RegisterPartial.cshtml
#model RegisterViewModel
#using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="NewPassword" class="control-label"></label>
<input asp-for="NewPassword" class="form-control" />
<span asp-validation-for="NewPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="NewPasswordAgain" class="control-label"></label>
<input asp-for="NewPasswordAgain" class="form-control" />
<span asp-validation-for="NewPasswordAgain" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="CreateAccount" class="btn btn-primary" />
</div>
}
Test Model Classes
public class LoginViewModel
{
[Required]
public string Username { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
}
public class RegisterViewModel
{
[Required]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string NewPassword { get; set; }
[Compare("NewPassword")]
[DataType(DataType.Password)]
public string NewPasswordAgain { get; set; }
}
Test Result

How Can I Get ViewData in PartialView in Razor Pages

I'm Using Razor Pages For my App, in one part of my app I've used a partial view here is my codes;
public class Permission
{
[Key]
public int PermissionId { get; set; }
public string PermissionTitle { get; set; }
public int? ParentID { get; set; }
}
public class IndexModel : PageModel
{
public PartialViewResult OnGetCreateRole()
{
var ListPermission = permissionService.AllPermission();
return new PartialViewResult()
{
ViewName = "_PCreateRole", // partial's name
ViewData = new ViewDataDictionary<List<Permission>>(ViewData,
ListPermission)
};
}
}
ViewData is a List of Permission class and i've sent ViewData to partial but i dont know how to get ViewData, also my partial use another model, below is my partial:
#model ToMVC.DataLayer.Entities.User.Role
<div class="row">
<div class="col-md-12">
<form asp-page="CreateRole" method="post">
<div class="form-group">
<label class="control-label">Title</label>
<input asp-for="RoleTitle" class="form-control"/>
<p><span class="text-danger" asp-validation-for="RoleTitle"></span></p>
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-primary" />
</div>
//this part needs ViewData
#foreach (var item in ViewData)
{
}
</form>
</div>
</div>
I want to use ViewData in Foreach loop.
A better solution than ViewData would be to simply make a new ViewModel class containing all the information you need for a view.
public class UserRoleAndPermissions{
public UserRoleAndPermissions(){
Permissions = new List<Permissions>();
}
public List<Permission> Permissions {get;set;}
public ToMVC.DataLayer.Entities.User.Role Role {get;set;}
}
And your view
//check your namespace here - this is just an example
#model ToMVC.DataLayer.UserRoleAndPermissions
<div class="row">
<div class="col-md-12">
<form asp-page="CreateRole" method="post">
<div class="form-group">
<label class="control-label">Title</label>
<input asp-for="RoleTitle" class="form-control"/>
<p><span class="text-danger" asp-validation-for="RoleTitle"></span></p>
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-primary" />
</div>
#foreach (var item in Model.Permissions)
{
}
</form>
</div>
</div>

How to configure Checkboxes Materialize Css in Web application Asp.Net MVC

How do I configure Checkboxes in Asp.Net MVC Razor.
Since in the documentation we have the following configuration Materialize for checkboxes :
<p>
   <label>
     <input type = "checkbox" />
     <span> Network </span>
   </label>
</p>
And in Razor I could not perform this configuration.
<div class = "input-field col s12">
        #Html.EditorFor (model => model.AnnualDestaque)
        #Html.LabelFor (model => model.AnnualDestaque)
        #Html.ValidationMessageFor (model => model.AnnualDestaque, "", new {#class = "text-danger"})
</div>
Please include model Name in your cshtml page
#model WebApplication3.Models.Test
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("Save", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-md-4">
#Html.TextBoxFor(m => m.EmployeeName)
#Html.CheckBoxFor(m=>m.IsSelected)
</div>
<input type="submit" value="Save" />
</div>
}
Model
public class Test
{
public string EmployeeName { get; set; }
public bool IsSelected { get; set; }
}
If you just want to have a checkbox binded with your model like that :
public class Network
{
public bool Selected { get; set; }
public string Name { get; set; }
}
Just use :
#Html.CheckBoxFor(m=>m.Selected)
#Html.LabelFor(m=>m.Name)
I was able to solve it, and I am passing the answer.
I used Html Helper Documentation Html Helper MVC
It worked perfectly without mistakes the way it's meant to be.
<div class="input-field col s12">
<label>
<input data-val="true"
data-val-required="The Advertisement field is required."
id="Advertisement"/**** m => m.Advertisement ****/
name="Advertisement"/**** m => m.Advertisement ****/
type="checkbox"
value="true" />
<span>Anuncio Destaque</span>
<input name="Advertisement" type="hidden" value="false" />
</label>
</div>
You can make it work doing this:
<label>
<input type="checkbox" name="FIELDNAME" id="FIELDNAME" value="true" class="filled-in" #(Model.FIELDNAME? "checked" : "") />
<span>#Html.DisplayNameFor(model => model.FIELDNAME)</span>
</label>
<input name="FIELDNAME" type="hidden" value="false" />

MVC Url.Action causes NullReferenceException in post

I'm trying to have a button on my form page that takes me back to the previous view that requires a parameter, I'm passing a ViewModel into the view with the assigned value I'm using. If the button is un-commented the button works fine but the forms post sends a NullReferenceException, and if the button is commented the form works exactly as I want.
The button that breaks the form
<button type="button" onclick="location.href='#Url.Action("Assignments","Session", new { Model.CourseName })'">Go Back</button>
The Controller Code
public IActionResult CreateAssignment(string courseName)
{
CreateAssignmentModel assignmentModel = new CreateAssignmentModel();
assignmentModel.CourseName = courseName;
return View(assignmentModel);
}
[HttpPost]
public IActionResult CreateAssignment(CreateAssignmentModel assignment)
{
if (ModelState.IsValid)
{
ModelState.Clear();
return View(assignment.CourseName);
}
else
{
return View(assignment.CourseName);
}
}
public IActionResult Assignments(string courseName)
{
var assignments = storedProcedure.getAssignments(User.Identity.Name, courseName);
var AssignmentsView = new AssignmentsViewModel{CourseName = courseName};
foreach (var Assignment in assignments.ToList())
{
AssignmentsView.Assignments.Add(Assignment);
}
return View(AssignmentsView);
}
The Model Code
public class CreateAssignmentModel
{
public string UserName { get; set; }
public string CourseName { get; set; }
[Required]
public string AssignmentName { get; set; }
[Required]
public string AssignmentDescription { get; set; }
[Required]
public int TotalPoints { get; set; }
[Required]
public DateTime DueDate { get; set; }
}
The Form with Button
<button type="button" onclick="location.href='#Url.Action("Assignments","Session", new { Model.CourseName })'">Go Back</button>
<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="#ViewData["ReturnUrl"]" method="post">
<h4>Create an Assignment</h4>
<hr />
<div class="form-group">
<label asp-for="AssignmentName" class="control-label">Assignment Name</label>
<input asp-for="AssignmentName" class="form-control" placeholder="Assignment Name" />
<span asp-validation-for="AssignmentName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="AssignmentDescription" class=" control-label">Assignment Description</label>
<input asp-for="AssignmentDescription" class="form-control" placeholder="Assignment Description" />
<span asp-validation-for="AssignmentDescription" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TotalPoints" class=" control-label">Total Points</label>
<input asp-for="TotalPoints" class="form-control" placeholder="Points" />
<span asp-validation-for="TotalPoints" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DueDate" class=" control-label">Due Date</label>
<input asp-for="DueDate" class="form-control" placeholder="Due Date" />
<span asp-validation-for="DueDate" class="text-danger"></span>
</div>
<br />
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</div>
Sorry for the lack of brevity, I've looked at NullReferenceException solutions for my problem but none have worked.

HttpPostedFileBase is Not Being Populated

I have a model (simplified, removing extraneous properties):
public class SubmitModel
{
[Required]
[DataType("FileUpload")]
[Display(Name = "Formatted Data File")]
public HttpPostedFileBase FormattedDataFile { get; set; }
}
A controller:
[HttpPost]
public ActionResult Submit(SubmitModel model)
{
if (this.ModelState.IsValid)
{
//...
}
return this.View(model);
}
A FileUpload view:
#{
IDictionary<string, object> htmlAttributes = Html.GetUnobtrusiveValidationAttributes(string.Empty);
}
<input type="file" id="#this.ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty)" name="#this.ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)" #(new MvcHtmlString(htmlAttributes.ToHtmlAttributesString())) />
#Html.ValidationMessage(string.Empty)
And a simple view:
#model SubmitModel
#using (Html.BeginForm())
{
<div class="Form">
#Html.EditorForModel()
<div class="Footer">
<button class="Button" data-options='{ "icons": { "primary": "ui-icon-disk" } }'>Submit</button>
</div>
</div>
}
Which renders to this HTML:
<form action="/Data/Submit" method="post">
<div class="Form">
<div class="Item">
<div class="Label Required">Formatted Data File:</div>
<div class="Input">
<input type="file" id="FormattedDataFile" name="FormattedDataFile" data-val-required="The Formatted Data File field is required." data-val="true" />
<span class="field-validation-error" data-valmsg-for="FormattedDataFile" data-valmsg-replace="true">The value 'Test.xlsx' is invalid.</span>
</div>
</div>
<div class="Footer">
<button class="Button" data-options='{ "icons": { "primary": "ui-icon-disk" } }'>Submit</button>
</div>
</div>
</form>
Upon clicking Submit, I'm brought to the proper controller/action and my model's FormattedDataFile property is null. The ModelState is invalid, saying that "The Formatted Data File field is required." This same code worked fine in some MVC-3 projects I've done - is there anything different regarding this in MVC-4?
i think you are missing enctype="multipart/form-data" in the form
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Resources