MVC with angular 2 - asp.net-mvc

I develop project mvc with angular 2. I use Identity in project. I have view of login after authorization I want redirect on my angular page.
public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
ApplicationUser user = await UserManager.FindAsync(model.Email, model.Password);
if (user == null)
{
ModelState.AddModelError("", "login ...");
}
else
{
ClaimsIdentity claim = await UserManager.CreateIdentityAsync(user,
DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignOut();
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = true
}, claim);
if (String.IsNullOrEmpty(returnUrl))
return RedirectToAction("Index", "Home");
return Redirect(returnUrl);
}
}
ViewBag.returnUrl = returnUrl;
return View(model);
}
Here my RouteConfig
routes.MapRoute(
name: "Logout",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Logout", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{*anothing}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
When redirecting, I do not go to the address /home of angular page is redirect on /Home/Index
RedirectToAction("Index", "Home")
Here my angular routing
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './components/home.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
Help me please, how I can do it right?
Here my index page and layout
#{
ViewBag.Title = "Index";
}
<body>
<user-app>Loading…</user-app>
</body>
//////////////////
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/systemjs.config.js"></script>
<script>
System.import('app').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>

Related

Update the value in a textbox with controller

In my ASP MVC web application. I have this controller
namespace Test.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index(UserDetails user)
{
user.UserEmail = "Email one";
return View(user);
}
// Post: Home
[HttpPost]
public ActionResult Index(UserDetails user, string command)
{
user.UserEmail = "Email two";
return View(user);
}
#region Helpers
#endregion
}
}
and this view
#model Test.Models.UserDetails
#{ Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DisplayNameFor(model => model.UserEmail)
#Html.EditorFor(model => model.UserEmail)
<input type="submit" name="Command" value="Search" class="btn btn-default" />
A}
</body>
</html>
When I first run the application it will show “Email one” in the textbox. But when I hit the submit button it will not change the value in the textbox to “Email two”. What I have to change on my code?

How to show entered order no and selected product name and id

i am new in mvc. so could not figure out what to add in code to show entered order no and selected product name and id.
here is full code and dotnetfiddle url https://dotnetfiddle.net/6vn2GO
Model code
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class OrderViewModel
{
[Display(Name = "Order number")]
public int? OrderNumber { set; get; }
[Display(Name = "Product")]
[Required(ErrorMessage = "Please select a product")]
public int SelectedProductId { set; get;}
public SelectList ProductList { get; set; }
}
public class Product
{
public int ID { set; get; }
public string Name { set; get; }
}
public static class Repository
{
public static IEnumerable<Product> FetchProducts()
{
return new List<Product>()
{
new Product(){ ID = 1, Name = "Ketchup" },
new Product(){ ID = 2, Name = "Mustard" },
new Product(){ ID = 3, Name = "Relish" }
};
}
}
}
Controller code
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
OrderViewModel model = new OrderViewModel();
model.OrderNumber=null;
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(OrderViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
// but for testing purposes
ConfigureViewModel(model);
return View(model);
}
private void ConfigureViewModel(OrderViewModel model)
{
IEnumerable<Product> products = Repository.FetchProducts();
model.ProductList = new SelectList(products, "ID", "Name");
}
}
}
View.cshtml code
#model HelloWorldMvcApp.OrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(m => m.OrderNumber)
#Html.TextBoxFor(m => m.OrderNumber, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.OrderNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.SelectedProductId)
#Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {#class="form-control"})
#Html.ValidationMessageFor(m => m.SelectedProductId)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
please tell me what code i need to add in view html to show entered order no and selected product name and id. thanks
You could set the value of your order number on the [HttpPost] Action method and check if it's null on the view side and show/hide stuff accordingly.
Another (probably better) alternative would be to just create a new view and return that when the model state is valid. To get the order number, you'll need to fetch the inserted ID from the database and pass that to the view.
Edit to show some code:
Controller Code:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
OrderViewModel model = new OrderViewModel();
model.OrderNumber=null;
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(OrderViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
// but for testing purposes
ConfigureViewModel(model);
// you'll need to figure out how you're generating your
// order numbers
//
model.OrderNumber = 1; // just set this statically for now for POC
return View(model);
}
private void ConfigureViewModel(OrderViewModel model)
{
IEnumerable<Product> products = Repository.FetchProducts();
model.ProductList = new SelectList(products, "ID", "Name");
}
}
}
View Code:
#model HelloWorldMvcApp.OrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
#{
if(Model.OrderNumber == null)
{
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(m => m.OrderNumber)
#Html.TextBoxFor(m => m.OrderNumber, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.OrderNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.SelectedProductId)
#Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {#class="form-control"})
#Html.ValidationMessageFor(m => m.SelectedProductId)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
</div>
} else {
<div>show your confirmation stuff here</div>
}
}
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
that will reuse the same view, though as I said, I'd recommend using a different view.

Viewbag is null in alert

i wrote behind code.
but Viewbag.message will show null in alert message .myvar is a variable.
i used breakpoint , myvar will set by Viewbag.message correctly. but it will be shown null in alert .
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#{string myvar = ViewBag.AlertMessage;}
#using (Ajax.BeginForm("action", "controller", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert('#ViewBag.AlertMessage'); //infact, it shows alert('');
}
</script>
<script type="text/javascript">
function Messsage() {
alert('#myvar'); // should show "hello there"
}
</script>
#using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert("#ViewBag.AjaxMessage");
}
</script>
<input type="submit" value="Submit" />
}
is the ViewBag.AlertMessage being defined in the controller action ?
you can replace the data by
#{string myvar = "hello there !";}
<script type="text/javascript">
function Messsage() {
alert('#myvar'); // should show "hello there"
}
</script>
or define your viewbag item in the action method behind the result
public ActionResult Index() {
ViewBag.AlertMessage = "hello there !"
return View();
}
Try setting the value for ViewBag.AlertMessage in controller action that returns the view on which you have defined the Ajax.Begin form.
eg
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
ViewBag.AlertMessage = "AjaxMessage.";
return View();
}
}
on Index view i have placed the following code, calling AjaxAction on Home Controller.
#using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert("#ViewBag.AjaxMessage");
}
</script>
<input type="submit" value="Submit" />
}

jQuery ui Dialog with PartialView will not validate (MVC3)

Can someone please help me.
I cannot get my jQuery ui-dialog to validate.
I have tried to find a solution on this site and countless others but although everyone seems to have some sort of solution, I cannot get any of them to work.
I understand that it can sometimes be difficult to describe a problem so I have written a complete application that contains the minimum necessary to hopefully make things clear.
In the VIEW, there is an alert("saved"); which I do not want to see as the Dialog should prevent this getting that far.
Any suggestions will be most gratefully received.
CONTACTMESSAGE
using System.ComponentModel.DataAnnotations;
namespace TestValidation.Models
{
public class ContactMessage
{
[Required(ErrorMessage = "Message is Requried")]
public string Message { get; set; }
}
}
CONTROLLER:
namespace TestValidation.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Edit()
{
return PartialView("MessageForm",
new ContactMessage{Message="Test"});
}
public ActionResult Save()
{
return Content("Saved");
}
}
}
VIEW:
#model TestValidation.Models.ContactMessage
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>ViewPage1</title>
<link href="#Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="Stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
</head>
<body>
Dialog
<div id="Placeholder" title=""></div>
</body>
</html>
<script type="text/javascript">
$(function () {
$("#Placeholder").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Save": function () {
$.post("/Home/Save",
$("#EditForm").serialize(),
function (data) {
alert("saved");
$("#Placeholder").dialog("close");
});
},
Cancel: function () { $(this).dialog("close"); }
}
});
$("#editButton").click(function () {
$("#Placeholder").html("")
.dialog("option", "title", "Edit Message")
.load("/Home/Edit/", function () {
$("#Placeholder").dialog("open");
});
});
});
</script>
PARTIAL VIEW:
#model TestValidation.Models.ContactMessage
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("null", "null", FormMethod.Post, new { id = "EditForm" }))
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)
</div>
}
just after loading form into DOM do this
jQuery.validator.unobbstrusive.parse(jQuery('#EditForm'));

mvc2 host on iis6 : The incoming request does not match any route

I have to host my project on iis6, I can not change iis setting on server.
So, I modified global.asax like below.
If I add a default.aspx and browse project I got error like : The incoming request does not match any route.
if I dont add default aspx I got HTTP Error 403.14
have any idea?
thanks
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}.aspx/{action}/{id}",
new { controller = "Home", action = "Index", id = "" } // Parameter defaults )
);
routes.MapRoute("Detail", // Route name
"{controller}.aspx/{action}/{id}/{sid}",
new { controller = "Home", action = "Index", id = "", sid="" } // Parameter defaults )
);
routes.MapRoute("ForGoogle", // Route name
"{controller}.aspx/{action}/{friendlyUrl}/{id}/{partialName}",
new { controller = "Home", action = "Index", friendlyUrl = "", id = "", partialName =""} // Parameter defaults )
);
routes.MapRoute(
"PostFeed",
"Feed/{type}",
new { controller = "Product", action = "PostFeed", type = "rss" }
);
}
Add an index.htm file which redirects to the right page. This has a side advantage: it does not require the webapp to be started, so it is possible to show an image or text while the webapp is started for the first time.
A fancy jquery "loading..."-page I use in some projects:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>(loading...)</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({ type: 'GET', url: 'Home.aspx', success: function() { location.href = 'Home.aspx'; } });
});
</script>
</head>
<body>
<div id="loading">
(show "loading..." text here)
</div>
</body>
</html>

Resources