Autor Beitrag
georgeboy
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Fr 04.12.20 09:29 
Hallo zusammen, ich bin neu in ASP.NET MVC, und möchte mit einem button, eine Action auslösen, "Call1". Irgendein Problem mit dem Routing oder etwas anderes. Folgendes hat nicht geklappt:

ausblenden volle Höhe C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Route2",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Call1", id = UrlParameter.Optional }
            );
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }

    }

public class HomeController : Controller
    {
        // GET: Home
        
        [HttpGet]
        public ActionResult Call1()
        {
            ViewBag.Message = "Message Yes ...";
            return View();
        }
        [HttpGet]
        public ActionResult Index()
        {
            
            return View()
        }
    }



ausblenden HTML-Dokument
1:
2:
3:
4:
@using (Html.BeginForm("Call1""Home", FormMethod.Get))
                {
                    <button>MeinButton1</button>
                }


Es erscheint immer folgende Fehlermeldung:

Die Ansicht "Call1" oder die entsprechende Gestaltungsvorlage wurde nicht gefunden, oder keines der Ansichtsmodule unterstützt die durchsuchten Speicherorte. Die folgenden Speicherorte wurden durchsucht:
~/Views/Home/Call1.aspx
~/Views/Home/Call1.ascx
~/Views/Shared/Call1.aspx
~/Views/Shared/Call1.ascx
~/Views/Home/Call1.cshtml
~/Views/Home/Call1.vbhtml
~/Views/Shared/Call1.cshtml
~/Views/Shared/Call1.vbhtml

Weiss jemand Rat ?
jfheins
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 918
Erhaltene Danke: 158

Win 10
VS 2013, VS2015
BeitragVerfasst: Fr 04.12.20 13:12 
Moin,
erstmal:
ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
  name: "Route2",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Home", action = "Call1", id = UrlParameter.Optional }
);

Das macht so (wie es da steht) wenig Sinn. Denn das entscheidende ist das url Ding, welches das Template für die URL darstellt und das ist gleich.
Einfach den zweiten block weglassen.

Welche Dateien gibt es denn in deinem Projekt? Eine der Dateien (z.B. "/Views/Home/Call1.cshtml") solltest du angelegt haben, damit das ganze funktioniert.
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Fr 04.12.20 14:13 
Das geht, aber eigentlich dachte ich, dass auf mein Click, die Controller Action Call1, auf der gleichen View arbeitet. Muss man für jeden Button, der im Controller bearbeitet wird, eine neue View anlegen ? Ich habe den HTML-Text für die neue Call1.cshtml, einfach von Index.cshtml kopiert ... Wenn man bei Call1 nur geringfügig verändert, doch nicht gleich eine neue View ...
jfheins
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 918
Erhaltene Danke: 158

Win 10
VS 2013, VS2015
BeitragVerfasst: Fr 04.12.20 17:47 
user profile icongeorgeboy hat folgendes geschrieben Zum zitierten Posting springen:
Das geht, aber eigentlich dachte ich, dass auf mein Click, die Controller Action Call1, auf der gleichen View arbeitet. Muss man für jeden Button, der im Controller bearbeitet wird, eine neue View anlegen ? Ich habe den HTML-Text für die neue Call1.cshtml, einfach von Index.cshtml kopiert ... Wenn man bei Call1 nur geringfügig verändert, doch nicht gleich eine neue View ...

Nee, musst du nicht. Es wird einfach standardmäßig eine View gesucht, die genau so heißt wie die Controller Methode.

Du kannst eine beliebige View nutzen, wenn du den Namen übergibst: docs.microsoft.com/e...tring_System_Object_

ausblenden C#-Quelltext
1:
return View("OtherName", myModel);					
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Sa 05.12.20 08:45 
Also wirklich, die freundliche Entwickler-Ecke, macht ihrem Namen alle Ehre !!! Vielen Dank !!! Wer weiss vielleicht komme ich hier nochmal .. Leider habe ich nach langem Suchen, solche grundlegende Dinge nirgendwo gefunden. Bei einem Tutorial oder Buch, müsste mit solchen Dingen, begonnen werden, und dann erst in die Tiefe gegangen werden. Wenn man von C# .NET kommt, hat man als erstes Ereignisse und Event-Händler im Kopf. Also nochmals vielen Dank !!!
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Sa 05.12.20 16:21 
Jetzt doch noch was, wie geht man beim HTML Steuerelement "select" im Controller vor ? Eine Dokumentation für andere Steuerelemente ? Ein Link, oder noch besser ein Buch ...
jfheins
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 918
Erhaltene Danke: 158

Win 10
VS 2013, VS2015
BeitragVerfasst: So 06.12.20 08:10 
Ich habe das damals aus diesen Videos gelernt: channel9.msdn.com/Se...ction-to-ASP-NET-MVC kann ich nur weiterempfehlen.

Aber wenn du jetzt einsteigst, würde ich dir ganz allgemein von asp.net MVC abraten. Das wurde mehr oder weniger ersetzt durch asp.net core MVC: docs.microsoft.com/d...?view=aspnetcore-5.0

.net core ist der de-facto Nachfolger von .net Framework, vom Framework wird es wohl keine neuen Versionen geben.
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: So 06.12.20 14:27 
Habe noch folgendes gefunden:

My view has a Select with elements(options) from my ViewModel.

ausblenden HTML-Dokument
1:
2:
3:
4:
5:
6:
7:
8:
9:
@using (Html.BeginForm("NewUser""Admin"))
        {
             <select multiple="" id="inputRole" class="form-control" size="6" name="inputRole">
             @foreach (var item in Model.roller)
             {
                 <option>@item.Name</option>
             }
             </select>
         }



How can i get the selected value in my Controller?

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
[HttpPost]
    public ActionResult NewUser(FormCollection formCollection)
    {
        String roleValue1 = formCollection["inputRole"];
    }


Das klappt bei "select". wie geht es bei einer Combobox ? Da gibt es auch noch "@Html.<Controls>, gibt es eine umfassende Dokumentation dazu ?
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: So 06.12.20 14:33 
Mit ASP.NET Core möchte ich mich auch noch befassen, hätte gern ein gutes Buch oder Link dazu. Aber zuerst muss da etwas über die einfachen Dinge, über die wir hier geschrieben haben, drinstehen ... Erste einfache Beispiele, und dann in die Tiefe, nicht andersherum ...
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: So 06.12.20 15:59 
Klappt doch nicht "NewUser" wird nicht aufgerufen, Sowohl "Get" als auch "Post", Die listbox erscheint korreckt, beim draufclicken sollte das Ereignis ausgelöst werden ..

ausblenden HTML-Dokument
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
<div>
        @using (Html.BeginForm("NewUser""Home", FormMethod.Get))
        {
        <select multiple = "" id = "inputRole" name = "inputRole" class="form-control" size="6">
                
                     @foreach (var s in Model.li)
                     {
                        <option>@s</option>
                     }
        </select>
        }
</div>


ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
[HttpGet]
        public ActionResult NewUser(FormCollection formcollection)
        {
            ViewBag.Message ="MeinSelect";
            //ViewBag.Message = (string)formcollection["inputRole"];
            return View("Index"new Models.MyModel());
        }
jfheins
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 918
Erhaltene Danke: 158

Win 10
VS 2013, VS2015
BeitragVerfasst: So 06.12.20 21:02 
user profile icongeorgeboy hat folgendes geschrieben Zum zitierten Posting springen:
Die listbox erscheint korrekt, beim draufclicken sollte das Ereignis ausgelöst werden ..

Hast du auch einen Submit button? Zeig mal mehr von deiner View

Zitat:
Mit ASP.NET Core möchte ich mich auch noch befassen, hätte gern ein gutes Buch oder Link dazu. Aber zuerst muss da etwas über die einfachen Dinge, über die wir hier geschrieben haben, drinstehen

Das macht jetzt nicht sooo viel Sinn, weil das ja nicht unmittelbar aufbaut. Das ist als würde man sagen "Ich möchte später schon gerne den neuen 3er BMW fahren, aber jetzt lerne ich erstmal den alten 3er BMW zu fahren für die Grundlagen..."
Die Komplexität ist die gleiche, nur das eine Mal muss man danach direkt umlernen...
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Mo 07.12.20 08:56 
Der Viewtext stammt zum Teil noch von unserem älteren Beispiel:

View:
=====

ausblenden volle Höhe HTML-Dokument
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
@{
    ViewBag.Title = "View";
}

@{ 
    Layout = null;
}

<!DOCTYPE html>
<html>
    <head>
        <!-- meta name="viewport" content="width=device-width" />
        <title>Ueberschrift</title> -->

    </head>
    <body>
        <h1>MeineAnzeige</h1>
        <div class="jumbotron">
            <h1>ASP.NET</h1>
            <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
            <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
        </div>
        
        @ViewBag.Message
        
        <div>
        @*@using (Html.BeginForm("NewUser""Home"))
        {
        <select multiple="" id="inputRole" name="inputRole" class="form-control" size="6">

                     @foreach (var s in Model.li)
                     {
                        <option>@s</option>
                     }
        </select>
        <!-- Hier kam die Meldung: "/Home/NewUser" nicht gefunden -->
        }*@

       <select multiple="" id="inputRole" name="inputRole" class="form-control" size="6"
               onchange="location.href='@Url.Action("NewUser", "Home")'">
            @foreach (var s in Model.li)
            {
                <option>@s</option>
            }
       </select>

     </div>
        
        <div class="row">
            <div class="col-md-4">
                @using (Html.BeginForm("Index""Home", FormMethod.Get))
                {
                    <input type="Text" name="demotextbox" autocomplete="off" />
                }

                
                @*<button method="get" action="/Home/Call1">Mein Button</button>*@

                @using (Html.BeginForm("Call1""Home", FormMethod.Get))
                {
                    <button>MeinButton1</button>
                }
                

                @if (Model.IndexValid)
                {
                    <p>String gefunden an Index @Model.StringIndex</p>
                }
                else
                {
                    <p>String nicht gefunden</p>
                }
            </div>
        </div>
    </body>
</html>


Controller:
===========

ausblenden volle Höhe C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NeuerTest1.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        private static List<string> ExampleStrings = new List<string>
        {
            "Test""Hallo""Welt""Entwickler""Ecke"
        };

        [HttpGet]
        public ActionResult Index(string demotextbox = null)
        {
            //ViewBag.Message = "Erste Meldung";
            var listIdx = ExampleStrings.IndexOf(demotextbox);
            return View(new Models.MyModel { StringIndex = listIdx });
        }

        [HttpGet]
        public ActionResult Call1(string id)
        {
            ViewBag.Message = "Message Yes 200 ...";
            return View("Index"new Models.MyModel());
        }

        [HttpGet]
        public ActionResult NewUser(FormCollection formcollection)
        {
            ViewBag.Message ="MeinSelect";
            //ViewBag.Message = formcollection["inputRole"]; //["inputRole"];
            return View("Index"new Models.MyModel()); 
        }


    }
}
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Mo 07.12.20 09:05 
Die Action Methode: "NewUser" wird aufgerufen, nur der Eintrag vom Select-Feld wird nicht angezeigt, bei:

ausblenden C#-Quelltext
1:
ViewBag.Message = formcollection["inputRole"];					
jfheins
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 918
Erhaltene Danke: 158

Win 10
VS 2013, VS2015
BeitragVerfasst: Mo 07.12.20 11:39 
Soweit so klar ;-)

In HTML brauchst du (ohne JS) immer ein Formular, um Daten an den Server zu senden. Wenn du das dann abschickst, werden alle Felder dieses Formulars geschickt.
Du machst aber ständig neue Mini-Formulare auf, da kommt dann natürlich wenig an.

ausblenden HTML-Dokument
1:
2:
3:
4:
5:
6:
7:
       <select multiple="" id="inputRole" name="inputRole" class="form-control" size="6"
               onchange="location.href='@Url.Action("NewUser", "Home")'">
            @foreach (var s in Model.li)
            {
                <option>@s</option>
            }
       </select>

Du hast hier komplett auf ein Formular verzichtet, d.h. du musst eigentlich alles selber machen. Du trägst aber nur einen onChange Handler ein, der die URL direkt auf @Url.Action("NewUser""Home") setzt. URL.Action weiß ja nix von dem select element, das gibt einfach nur URLs aus. Den Wert deines dropdowns ignorierst du.
Also entweder das Formular richtig benutzen, oder eine JS Funktion schreiben, die das dropdown ausliest und die Werte mit einem XMLHttpRequest verschickt.

Im Controller brauchst du auch nicht NewUser(FormCollection formcollection) zu schreiben und die Werte rauslesen, du kannst einfach NewUser(int inputRole) schreiben (oder halt der richtige Typ, den die Werte im Dropdown haben).
Die Zuordnung Formular-Werte <> Methoden Argumente funktioniert automatisch.

Mehr Infos zu Formularen: wiki.selfhtml.org/wiki/HTML/Formulare/form
Oder hier gibt es auch viele Infos: docs.microsoft.com/d...ta-from-a-controller
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Mo 07.12.20 15:23 
Unklar, tut mir leid so ganz verstanden habe ich das noch nicht..
Meine neue Version:


ausblenden volle Höhe HTML-Dokument
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
@{
    ViewBag.Title = "View";
}

@{ 
    Layout = null;
}

<!DOCTYPE html>
<html>
    <head>
        <!-- meta name="viewport" content="width=device-width" />
        <title>Ueberschrift</title> -->

    </head>
    <body>
        <h1>MeineAnzeige</h1>
        <div class="jumbotron">
            <h1>ASP.NET</h1>
            <p class="lead">ASP.NET is a free web framework for building great Web sites 
                      and Web applications using HTML, CSS and JavaScript.</p>
            <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
        </div>
        
        @ViewBag.Message
        
        <div>
   
     </div>
        
        <div class="row">
            <div class="col-md-4">
                @using (Html.BeginForm("Index""Home", FormMethod.Get))
                {
                    <input type="Text" name="demotextbox" autocomplete="off" />
                    
                    <select multiple="" id="inputRole" name="inputRole" class="form-control" size="6">
                        @foreach (var s in Model.li)
                        {
                            <option>@s</option>
                        }
                    </select>
                    
                    <button type="submit">MeinButton1</button>
                    <br/><br/>
                }
                
                @if (Model.IndexValid)
                {
                    <p>String gefunden an Index @Model.StringIndex</p>
                }
                else
                {
                    <p>String nicht gefunden</p>
                }
            </div>
        </div>
    </body>
</html>


ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
public ActionResult Index(string demotextbox = nullstring Select1)
        {
            ViewBag.Message = "Erste Meldung" + Select1;
            var listIdx = ExampleStrings.IndexOf(demotextbox);
            return View(new Models.MyModel { StringIndex = listIdx });
        }


Es kommt die Fehlermeldung:

Schweregrad Code Beschreibung Projekt Datei Zeile Unterdrückungszustand
Fehler CS1737 Optionale Parameter müssen nach allen erforderlichen Parametern angezeigt werden. NeuerTest1 C:\Projekte\Web\NeuerTest1\Controllers\HomeController.cs 18 Aktiv
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Mo 07.12.20 15:33 
Hier noch das Model:

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NeuerTest1.Models
{
    public class MyModel
    {
        static MyModel()
        {

        }

        public List<string> li = new List<string>
            { "MeinErster""MeinZweiter""MeinDritter""MeinVierter"};
        public int StringIndex { get; set; }
        public bool IndexValid => StringIndex >= 0;
    }
}
georgeboy Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 198



BeitragVerfasst: Mo 07.12.20 17:26 
Jetzt habe ich es verstanden, so gehts:

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
[HttpGet]
        public ActionResult Index(string demotextbox = nullstring inputRole = null)
        {
            ViewBag.Message = inputRole; 
            var listIdx = ExampleStrings.IndexOf(demotextbox);
            return View(new Models.MyModel { StringIndex = listIdx });
        }



Und nochmals, Vielen Dank !!! So sehr möchte ich mich gar nicht vertiefen, nur gewisse grundlegende Dinge verstehen. Mit den Büchern über MVC un Core bin ich nicht zurechtgekommen, hätte dafür gar nichts bezahlen sollen. Deine Lösungen sind mehr Wert.