greenasil greenasil - 20 days ago 4x
C# Question

Using out parameters and getting pass by reference error

I am building an MVC application that sends mock text messages, and in it I have two models: Contacts and Textmessages.

When the user creates a Textmessage, the view requires that they enter a phone number and their message. When submitted, the controller verifies if the phone number (contact) exists in the database before allowing the message to be created.

If the contact exists, the confirmation screen needs to display the message details (phone number and message) as well as the name of the recipient.

I'm using out parameters to send back the name info as strings, but I am getting an error:

Cannot call action method 'System.Web.Mvc.ActionResult Create(SMSText.Models.Textmessage, System.String ByRef, System.String ByRef)' on controller 'SMSText.Controllers.TextmessagesController' because the parameter 'System.String& firstName' is passed by reference.

Here is the code I am using:

public ActionResult Create( [Bind(Include =
"ID,Message,EnteredPrefix,EnteredPhoneNumber")] Textmessage textmessage,
out string firstName, out string surName )
firstName = "";
surName = "";

if (ModelState.IsValid)
bool exists = db.Contacts.AsEnumerable()
.Where(contact => contact.AreaCode == textmessage.EnteredPrefix && contact.PhoneNumber == textmessage.EnteredPhoneNumber)
.Count() >0;

if (exists)
var contactObj = db.Contacts.First(contact => contact.AreaCode == textmessage.EnteredPrefix && contact.PhoneNumber == textmessage.EnteredPhoneNumber)
firstName = contactObj.Forename;
surName = contactObj.Surname;

return RedirectToAction("Details", textmessage );
return View("Error", textmessage);
return View(textmessage);

If I understand the error message, the name info is being passed as a reference rather than as an actual string, but I do not know how to fix this.

How can I get past this error? Is there a better method to accomplish what I am doing?


Looks like you are unnecessarily over-killing the call by trying to use out parameters. Why dont you simple use the ViewData once you find the matching contact and then use in the view?

var contact  = db.Contacts.AsEnumerable()
                .Where(contact => contact.AreaCode == textmessage.EnteredPrefix && contact.PhoneNumber == textmessage.EnteredPhoneNumber);

if(contact != null && contact.Any())
   ViewData["Contact"] = contact.FirstOrDefault();
   return RedirectToAction("Details", textmessage );

and then in the view you can read it back:

    var contact = (Contact)ViewData["Contact"];

Please let me know how did it work for you...