Click here to Skip to main content
15,876,993 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How to get the value of input field from View to MyController
here is my View code:

HTML
<label class="w-100">Username</label> 
<input id="empUsername" class="input-form w-100" disabled>


Here is my code in Controller:

ASP.NET
[HttpPost]
      public IActionResult OnPostMyUploader(IFormFile MyUploader)
      {
          // No point loading and resizing the image if we're not going to use it:
          if (MyUploader is null) return new ObjectResult(new { status = "fail" });

          string uploadsFolder = @"\\10.10.10.67\AQSImages\IdPictures\";
          string userfileName = I WANT TO USE THAT VALUE HERE SO I CAN STORE HERE
          string filePath = Path.Combine(uploadsFolder, userfileName);
          using var fileStream = new FileStream(filePath, FileMode.Create);

          using var image = System.Drawing.Image.FromStream(MyUploader.OpenReadStream());
          using var resized = new Bitmap(image, new System.Drawing.Size(150, 150));
          using var imageStream = new MemoryStream();
          resized.Save(imageStream, ImageFormat.Jpeg);


          // Reset the current position of the stream:
          imageStream.Seek(0L, SeekOrigin.Begin);
          imageStream.CopyTo(fileStream);
          return new ObjectResult(new { status = "success" });
      }


What I have tried:

Getting Data From View to Controller in MVC[^]
Posted
Updated 9-Jul-22 2:26am
Comments
Dave Kreskowiak 6-Jul-22 19:50pm    
You already asked that question at https://www.codeproject.com/Questions/5336589/How-to-get-the-value-from-view-to-controller.

...and are ignoring the answer given? If not, continue the discussion on the previous thread. Do not open another copy of the same question.

1 solution

Using Traditional Approach
 
In the traditional approach we use the request object of the HttpRequestBase class. The request object has view input field values in name/value pairs. When we create a submit button then the request type POST is created and calls the POST method.
 
MVC1.jpg 
Figure 1.2 Requested Data
 
We have four data, those are in Name-Value pairs. So we can access these data in a POST method by passing the Name as an indexer in the Request and get values. Our POST method means the controller action that handles the POST request type is [HttpPost].
[HttpPost]  
public ActionResult CalculateSimpleInterestResult()  
{  
    decimal principle = Convert.ToDecimal(Request["txtAmount"].ToString());  
    decimal rate = Convert.ToDecimal(Request["txtRate"].ToString());  
    int time = Convert.ToInt32(Request["txtYear"].ToString());  
   
    decimal simpleInteresrt = (principle*time*rate)/100;  
   
    StringBuilder sbInterest = new StringBuilder();  
    sbInterest.Append("Amount : " + principle+"<br/>");  
    sbInterest.Append("Rate : " + rate + "<br/>");  
    sbInterest.Append("Time(year) : " + time + "<br/>");  
    sbInterest.Append("Interest : " + simpleInteresrt);  
    return Content(sbInterest.ToString());  
}  
When it executes, we get simple interest as the result as in the following:
 
MVC2.jpg 
Figure 1.3 Output screen after getting response
 
Using the FormCollection Object
 
We can also get post requested data by the FormCollection object. The FormCollection object also has requested data in the name/value collection as the Request object. To get data from the FormCollection object we need to pass it is as a parameter and it has all the input field data submitted on the form. 
[HttpPost]  
  
public ActionResult CalculateSimpleInterestResult(FormCollection form)  
{  
    decimal principle = Convert.ToDecimal(form["txtAmount"].ToString());  
    decimal rate = Convert.ToDecimal(form["txtRate"].ToString());  
    int time = Convert.ToInt32(form["txtYear"].ToString());  
   
    decimal simpleInteresrt = (principle*time*rate)/100;  
   
    StringBuilder sbInterest = new StringBuilder();  
    sbInterest.Append("Amount : " + principle+"<br/>");  
    sbInterest.Append("Rate : " + rate + "<br/>");  
    sbInterest.Append("Time(year) : " + time + "<br/>");  
    sbInterest.Append("Interest : " + simpleInteresrt);  
    return Content(sbInterest.ToString());  
} 
It also gives the same output as Figure 1.3 shows.
 
Using the Parameters
 
We can pass all input field names as a parameter to the post action method. The input field name and parameter name should be the same. These parameters have input field values that were entered by the user. So we can access view input field values from these parameters. The input field takes a string value from the user so the parameter should be a string type. There is no need to define a parameter in any specific sequence. 
[HttpPost]  
public ActionResult CalculateSimpleInterestResult(string txtAmount, string txtRate, string txtYear)  
{  
    decimal principle = Convert.ToDecimal(txtAmount);  
    decimal rate = Convert.ToDecimal(txtRate);  
    int time = Convert.ToInt32(txtYear);  
   
    decimal simpleInteresrt = (principle*time*rate)/100;  
   
    StringBuilder sbInterest = new StringBuilder();  
    sbInterest.Append("Amount : " + principle+"<br/>");  
    sbInterest.Append("Rate : " + rate + "<br/>");  
    sbInterest.Append("Time(year) : " + time + "<br/>");  
    sbInterest.Append("Interest : " + simpleInteresrt);  
    return Content(sbInterest.ToString());  
}  
It also gives the same output as Figure 1.3 shows.
 
In all three approaches above we are parsing the string to a non-string type. If any of the parsing attempts fail then the entire action will fail. We are converting each value to avoid an exception but it also increases the amount of code. So we look at the fourth approach that would reduce the amount of code.
 
Strongly type model binding to view
 
We bind a model to the view; that is called strongly type model binding.
 
Step 1
 
Create a Model for Simple Interest
namespace CalculateSimpleInterest.Models  
{  
    public class SimpleInterestModel  
    {  
        public decimal Amount { get; set; }  
        public decimal Rate { get; set; }  
        public int Year { get; set; }  
    }  
}  
Step 2
 
Create an action method that render a view on the UI
 
We are passing an empty model to be bound to the view.
public ActionResult SimpleInterest()  
{  
    SimpleInterestModel model = new SimpleInterestModel();  
    return View(model);  
}  
Step 3
 
Create a strongly typed view that has the same screen as in Figure 1.1
@model CalculateSimpleInterest.Models.SimpleInterestModel  
   
@{  
    ViewBag.Title = "SimpleInterest";  
}  
   
<h2>Calulate Simple Interest</h2>  
   
@using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",  
                            new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))  
    {  
         
    <fieldset>  
        <legend>Calulate Simple Interest</legend>  
        <div id="divInterestDeatils"></div>  
   
        <div class="editor-label">  
            @Html.LabelFor(model => model.Amount)  
        </div>  
        <div class="editor-field">  
            @Html.EditorFor(model => model.Amount)            
        </div>  
   
        <div class="editor-label">  
            @Html.LabelFor(model => model.Rate)  
        </div>  
        <div class="editor-field">  
            @Html.EditorFor(model => model.Rate)            
        </div>  
   
        <div class="editor-label">  
            @Html.LabelFor(model => model.Year)  
        </div>  
        <div class="editor-field">  
            @Html.EditorFor(model => model.Year)             
        </div>  
        <p>  
            <input type="submit" value="Calculate" />  
        </p>  
    </fieldset>  
}  
   
@section Scripts {  
    @Scripts.Render("~/bundles/jqueryval")  
}  
Step 4
 
Create an action method that handles the POST request and processes the data
 
In the action method we pass a model as the parameter. That model has UI input field data. Here we do not need to parse and do not need to write extra code.
[HttpPost]  
public ActionResult CalculateSimpleInterestResult(SimpleInterestModel model)  
{  
    decimal simpleInteresrt = (model.Amount*model.Year*model.Rate)/100;  
    StringBuilder sbInterest = new StringBuilder();  
    sbInterest.Append("Amount : " + model.Amount+"<br/>");  
    sbInterest.Append("Rate : " + model.Rate + "<br/>");  
    sbInterest.Append("Time(year) : " + model.Year + "<br/>");  
    sbInterest.Append("Interest : " + simpleInteresrt);  
    return Content(sbInterest.ToString());  
}  
It also gives the same output as Figure 1.3 shows.
 
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