Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have tried the Visual Studio Create New Website option where you can write in a two main text files - one with extension cs for the c# code and one with aspx for the html, css, javascript and ASP markup code. You can easily access the html controls from the cs code when you add a property runat=server. I assume this is the so called Web Form model although I used the Create New Website and not the Create New Web Form Application. I have read that the new .NET 5 will not be available for the Web Form, but only for the MVC model. I'm trying to figure out MVC model, but it's way more complicated than I could think of, even for the simplest tasks. I have a few question which I can't answer myself and are involving the server-side (I know that you can just use javascript client-side for some of this - not what is intended):

1. Is is possible to access the content of a html elements by the server code when you press a button? The scenario I have used in ASP.NET Website is - placing a property that the label and button are server controls (without the asp markup) in a form and using their id to access them from the code. On the button I have the event onserverclick, which is defined in the cs file.

Sample:

.aspx
ASP.NET
<label id="labelID" runat="server">Text Which I Will Change</label>
<button id="buttonID" runat="server" onserverclick="changeLabelText">ChangeButton</button>


.cs
C#
public void changeLabelText (object sender, EventArgs e)
    {
        labelID.InnerText = "I Just Changed The Label Text";
    }


2. If such thing is possible with a HttpPost or some other way then the second question which involves the same concept is - is it possible doing so only on part of the page without needing to update the whole page? For instance I'm using the ScriptManager and UpdatePanel from AJAX ToolKit so when the button is pressed the page refreshes only the content of the UpdatePanel with Asynchronous Post Back.

Sample:

.aspx
ASP.NET
<form id="form" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<h1>Header Text</h1>
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<label id="labelID" runat="server">Text Which I Will Change</label>
</ContentTemplate>
</asp:UpdatePanel>  
<button id="buttonID" runat="server" onserverclick="changeLabelText">ChangeButton</button>
</form>


.cs
C#
public void changeLabelText (object sender, EventArgs e)
    {
        labelID.InnerText = "I Just Changed The Label Text";
        UpdatePanel.Update();
    }


Or may be if it's not possible the easy way then is there at least something like <%@ MaintainScrollPositionOnPostback="true" %> to maintain the previous position on post back.

3. Is is possible and where you can make it possible to write a server-side method for manipulating html input from the user - from the so called viewer? I have used the build in gridview in the ASP.NET Website. I could use the model to write a function with the classic ADO.NET (I'm using it, since it's simple and it's allowing you to write TSQL dynamically and freely) which I call in the viewer after passing the model through the controller, and then displaying it with a cycle with html tags. I know only the number of columns of the table in the database, but not how many fields/rows are there. I'm wondering is there a simple solution of editing any of the fields/rows - may be through html textbox, in which they will be written and then updating them with binding with DataTable or with manual loop, or at least one by one with a button on the side.

4. If the above is possible then is there a way of manipulating the same way on the server-side the CSS of the html (additionally)?

I see MVC is not event driven, but I guess since it's "better" than the ASP.NET Website and since the same will not get anymore further in .NET there is way to do such simple tasks. In my search I could find out, but not certainty that you can use a form or or no, but you cannon simple use standard html in the viewer. You have to use another technologies and manually do what is already done in ASP.NET Website variant (I guess in the controller with HttpPost), but there isn't enough beginners-like guides to this technologies.

It would be helpful any information on any of the questions, further reading, quick notes as it's possible or not, it's way more work than using another ways for server-side editing and even recommendation of another platforms and languages allowing these easy server-side tasks. The main goal is somewhat simple and fast development. Thanks.

/*
1. As for now I could only use a ViewData as for a text between the label:

.cshtml
HTML
<label id="labelID">@ViewData["labelText"]</label>
<form action="/Home/Change" method="post">
<input id="buttonID" type="Submit">ChangeButton</input>
</form>


.cs
C#
[HttpPost]
public ActionResult Change ()
{
    ViewData["labelText"] = "I Just Changed The Label Text";
    return View("ChangeView");
   /*same View but with this HttpPost has another label text*/
}


2. I could use jQuery AJAX, but had to manually pass a value, not just refresh the page part:

.cshtml
HTML
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
    function ajaxPostAndChange(buttonClicked) {
        var $form = $(buttonClicked).parents('form');
        $.ajax({
            type: "POST",
            url: '/Home/ChangeAjax',
            data: $form.serialize(),
            error: function (status, error) {
                alert("Status: " + status + ". Error: " + error + ".")
            },
            success: function (serverData) {
                document.getElementById("labelID").innerHTML = serverData;
            }
        });

    }
</script>
<label id="labelID">@ViewData["labelText"]</label>
<form>
<input id="buttonID" type="Button" onclick="ajaxPostAndChange(this)">ChangeButton</input>
</form>


.cs
C#
[HttpPost]
public object ChangeAjax()
{
    ViewData["labelText"] = "I Just Changed The Label Text";
    return ViewData["labelText"];
   /*same View but with this HttpPost has another label text*/
}


3. I could do the above with PartialView in the current View too and another action post method returning PartialViewResult, where I used another ViewData for writting on the server html with the @Html.Raw() for the PartialView. I guess if make a cycle with buttons with specific value for id of the current datatable field/row I can use it as input for a SQL command for Updating and then just loading the PartialView asynchronously (a lot of work for something taking a few minutes in ASP.NET Website with the build in GridView and AjaxToolKit).

4. The closest to getting a html control was using the name of the element of a form with FormCollection collection as parameter for the action method and then comparing collection.Get("inputName") values for changing a ViewData object which represented the value of the button. As I can see there is specific, but restricted controls for the MVC, which render themself as HTML, although they are only form controls and probably could allow you access them on the server, but not the way you can on the ASP.NET Website with runat="server" on a plain html.
*/
Posted
Updated 5-Dec-15 20:55pm
v2
Comments
F-ES Sitecore 7-Dec-15 4:28am    
You're not going to learn MVC from posts on a forum, and you're not going to get far if you think in terms of "what is the MVC equivalent for this webforms feature". Get a book on MVC and go through it, MVC is a different paradigm and needs a different mindset. It can be hard to go from webforms to MVC if you've relied on webforms to abstract the way http works without understanding what is going on under the covers, but you're not the first webforms developer to have this problem and you won't be the last.

Not sure that I would classify this as a solution, but I hope it would help you to understand a basic difference between webforms and mvc.

A real big difference between the two is the hidden fields which are maintained by webforms for passing data (state) back and forth between the server and the client. It is stored in a hidden field called __Viewstate ( https://msdn.microsoft.com/en-us/library/ms972976.aspx[^] )

If you were to use a tool like fiddler, you would see your form field values being passed as part of this string but not as separate keyvalue pair as part of the HttpRequest object.

something like:
__Viewstate="abcdxyz....&field_a=something&field_b=somethingelse


By contrast the MVC model is more of a classic post. Fiddler would show that each form field being sent with the post would have it's own key and value pair

field_a=somthing
field_b=somethingelse.

The mvc controller can map the request the request using the field names:

C#
[HttpPost]
public ActionResult Change(string field_a,string field_b)
{
    string a = field_a;
    string b = field_b;

}


Input fields which are defined inside of the form section will automatically be included posted back. Any fields outside the form section will not.

@using (Html.BeginForm("Login", "Account"))
{
    @Html.TextBox("Name");
    @Html.Password("Password");
    <input type="submit" value="Sign In">
}


This code will post back calling the Login method on the Account controller.
the HttpRequest object will include values for Name,Password

C#
public ActionResult Login(string Name,string Password)
{
    string a = Name;
    string b = Password;

}


Hope this helps,
Steve
 
Share this answer
 
Comments
Member 0123456789 7-Dec-15 2:31am    
I understand that Web Forms are doing almost everything behind the scene for you and in the MVC you have the full control of managing your resources, although it costs you more time/code and sometimes different approach. Thank you.
You need to read more about MVC. It is completely different world than Web Forms. Controllers are not codebehind of Views. Controller can change Models and pass it to the View or redirect to another View. You don't just access web controls from Controller and change them.

For example if a user submits a form, you catch it in Controller and see that Model state is invalid, you can add Model error to ModelState and redisplay a form with this data stored in the model. Than the View is the component that know how to display data properly, not Controller.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900