How do I access the variable of one method from another method within the same class C#?

user13860590

I'm working on Asp.net project. I created a Form, which asks for connectionId and holderFirstName as Input. The name of asp-action is SendProofNameRequest.

In Controller, I wrote a Method SendProofNameRequest which take connectionId and holderFirstName as Parameters. But the problem is, the purpose I'm taking holderFirstName as Input is to use this in another Method (VerifyFirstName).

So, my question is how to take holderFirstName as input from user and use this in another method / VerifyFirstName (not SendProofNameRequest).

Details.cshtml

    <form class="input-group mb-3" asp-controller="Proof" asp-action="SendProofNameRequest">
        <input type="hidden" name="connectionId" value="@Model.Connection.Id" />
        <input type="text" name="holderFirstName" autocomplete="off" class="form-control" placeholder="Enter First Name" aria-label="First Name" aria-describedby="basic-addon2">
        <div class="input-group-append">
            <button class="btn btn-outline-info" type="submit">Request a Proof of First Name</button>
        </div>
    </form> 

ProofController.cs

    [HttpPost]
    public async Task<IActionResult> SendProofNameRequest(string connectionId, out string holderFirstName)
    {
        var agentContext = await _agentProvider.GetContextAsync();
        var connectionRecord = await _walletRecordService.GetAsync<ConnectionRecord>(agentContext.Wallet, connectionId);
        var proofNameRequest = await CreateProofNameMessage(connectionRecord);
        await _messageService.SendAsync(agentContext.Wallet, proofNameRequest, connectionRecord);

        return RedirectToAction("Index");
    }

VerifyFirstName Method

I want to replace firstname (static value) with holderFirstName (dynamic value / user entered in form)

    public bool VerifyFirstName(PartialProof proof)
    {
        var firstName = "Fyodor";
        var name = proof.RequestedProof.RevealedAttributes.First();
        if (name.Value.Raw.Equals(firstName))
        { 
            return true; 
        }

        return false;
    }

UPDATE

As u said to add models, I did that... add the models in ViewModel page and call the @model in View page..

Now, to call the stored values in model in Verify methods controller.

VerifyProof(string proofRecordId) methods calls for another method VerifyFirstName(proof) which does the actual verification.

Kindly have a look at code and can u point out where to add model.HolderFirstName and SendNameRequestViewModel model in which method e.g. VerifyProof(string proofRecordId), VerifyFirstName(proof).. I was getting an errors..

    [HttpGet]
    public async Task<IActionResult> VerifyProof(string proofRecordId, SendNameRequestViewModel model)
    {
        var agentContext = await _agentProvider.GetContextAsync();
        var proofRecord = await _proofService.GetAsync(agentContext, proofRecordId);
        var request = JsonConvert.DeserializeObject<ProofRequest>(proofRecord.RequestJson);
        var proof = JsonConvert.DeserializeObject<PartialProof>(proofRecord.ProofJson);
        bool verified = false;
        switch (request.Name)
        {
            case "ProveYourFirstName":
                verified = VerifyFirstName(proof, model.HolderFirstName); break;
            default:
                    break;
        }
        if (!verified)
        {
            proofRecord.State = ProofState.Rejected;
            await _walletRecordService.UpdateAsync(agentContext.Wallet, proofRecord);
        }

        return RedirectToAction("Index");
    }

    public bool VerifyFirstName(PartialProof proof, SendNameRequestViewModel model.HolderFirstName)
    {
        var firstName = model.HolderFirstName;
        var name = proof.RequestedProof.RevealedAttributes.First();
        if (name.Value.Raw.Equals(firstName))
        { 
            return true; 
        }

        return false;
    }
David Liang

First of all, the actions/methods in the controller class are meant to handle requests coming from the client to the server. They're not just methods in a class.

Hence I think you need to take out out keyword from the parameter holderFirstName. Or better, to use a view model to pass between the view and the controller:

public class SendNameRequestViewModel
{
    [Required]
    public string ConnectionId { get; set; }

    [Required]
    public string HolderFirstName { get; set; }
}
public class ProofController : Controller
{
    public async Task<IActionResult> SendNameRequest(string connectionId)
    {
        // Initialize the view model if needed, i.e., filling its ConnectionId either
        // from query string or cache. I don't know how you get the connectionId

        var agentContext = await _agentProvider.GetContextAsync();
        var connectionRecord = await _walletRecordService.GetAsync<ConnectionRecord>(agentContext.Wallet, connectionId);
        if (connectionRecord == null)
        {
            return NotFound();
        }

        var vm = new SendNameRequestViewModel
        {
            ConnectionId = connectionId
        };
        return View(vm);
    }
}

Then on the view, you declare its model as SendNameRequestViewModel so that you don't have to hard code the input names/

Notes: I've also added validation summary and validation message for inputs.

@model SendNameRequestViewModel

...

<form class="input-group mb-3" method="post" asp-controller="Proof" asp-action="SendNameRequest">
    <input type="hidden" asp-for="ConnectionId" />

    <div asp-validation-summary="ModelOnly"></div>

    <input asp-for="HolderFirstName" autocomplete="off" class="form-control" 
      placeholder="Enter First Name" aria-label="First Name" aria-describedby="basic-addon2">
    <span asp-validation-for="HolderFirstName" class="text-danger"></span>

    <div class="input-group-append">
        <button class="btn btn-outline-info" type="submit">Request a Proof of First Name</button>
    </div>
</form>

For your VerifyFirstName check, there are so many way to do it. You can directly run its logic in the controller action body, for example. I would create an extension method against PartialProof object:

public static class PartialProofExtensions
{
    public static bool VerifyFirstName(this PartialProof proof, string firstName)
    {
        if (proof == null)
        {
            return false;
        }

        var name = proof.RequestedProof.RevealedAttributes
            .FirstOrDefault();

        return (name != null && name.Value.Raw.Equals(firstName));
    }
}

When the form is posting back, you can just run the validation check in the action method:

[HttpPost]
[ValidateAntiforgeryToken]
public async Task<IActionResult> SendNameRequest(SendNameRequestViewModel model)
{
    if (ModelState.IsValid)
    {
        var agentContext = await _agentProvider.GetContextAsync();
        var connectionRecord = await _walletRecordService.GetAsync<ConnectionRecord>(agentContext.Wallet, model.ConnectionId);
        if (connectionRecord == null)
        {
            ModelState.AddModalError("", "Invalid connection Id.");
            return View(model);
        }

        var proofNameRequest = await CreateProofNameMessage(connectionRecord);
        if (!proofNameRequest.VerifyFirstName(model.HolderFirstName))
        {
            ModelState.AddModalError(nameof(model.HolderFirstName), "Invalid first name.");
            return View(model);
        }

        await _messageService.SendAsync(agentContext.Wallet, proofNameRequest, connectionRecord);

        return RedirectToAction("Index");
    }

    return View(model);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Java - How do I get a variable generated from within a method in one class to another class?

How to pass a variable from one method to another in the same class?

How do I access a jQuery plugin variable from within method?

Access variable in another method from static method in same class

How do I access multiple objects from another method in the same class java?

How do I access the variable inside a class method from another python file?

How do I access an ArrayList from a previous method in the same class?

How do I call one method of an activity from another class

Calling one method from another within same class in Python

How do I export this variable from class method to another file?

Accessing variable from another method within the same class

How do I call a base class method from within the same overloaded derived class method in python?

How do I access a method expression (struct function) from within another method expression in Go / Golang?

Is there a way to transfer a value of an int from one object to another within the same class via method in c#

In Typescript how do I call a class method from another method in the same class that is called as an event handler

How can I access a class data member from a method within the same class?

Passing variable from another file and then use variable within to another method within same class

How do i reference a method from another class in C#?

How can I access a variable that is defined within the method in the class?

Why can't I access a public string from a method within the same class C#

How can I replace a variable in one method from another method

How to change a variable from within a method of another class Java

How can I access a Variable from within a Fuction (Method) that's in another Module

How do I access a non static method from main method in the same class?

How to access one class method from another class in dart?

How to allow only one class to access a method from another class?

How to call a method from same class in another method in C#?

Access a method within another method of the same class. Creating a Dynamic Array C++

How do I invoke a main() method of one class in another class?