0

I'm coming from an ASP.NET background and have started with ASP.NET MVC so not sure if I'm doing something wrong here or missing some fundamental understanding.

I have a PartialView as shown below:

@{
    Layout = "master.cshtml";
    ContactForm form= new ContactForm();
    form.Message = "Thank you, we shall be in touch";
}

I have my model with the Message property but is not being set in my controller only in the PV above. The purpose is the Message could be different for different forms.

I have a method which sends an email (this is fine and works, send all the fields from the form) but I would like the Message to be the one set in form.Message to be sent along when the form is submitted.

I read up on ViewBag but I think that's a temp value from the controller to the PV.

The code runs and sets the value for the Message on initial load which I established whilst debugging.

Once the method to send the email is reached (after clicking a button) all other fields are loaded except the Message value set on the PV.

How could I pass the Message from the partial view to my controller?

3 Answers 3

2

If you wish to send the value to the controller, once the form is submited, you must declare a hidden field for this message, bearing in mind that the hidden field must be placed inside the form, in order to be sent to the controller.

@using (Html.BeginForm("YourAction", "YourController", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Message)
    
    // Your form content comes here...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Actually you can send your model if you use HtmlTagHelper like this

@model List<Models.MyModel>

@Html.Partial("MyPartialName",@Model)

Absolutely you have to send your model from controller like this

public IActionResult Index()
{
.....
....
return View(MyModel);
}

you must create your partial .cshtml in Share folder. This is important

Comments

0

person.cs

   public class Person{
       public int Id {get;set;}
       public string personName {get;set;}
       public string contact {get;set;}
   }

MVC Controller

    public ActionResult YourMethod(Person){
         //Your Operations
   }
}

MainView.cshtml

<form action="YourMethod" method="post">
    <input type="text" name = "personName" >
    @Html.partial("PartialExample");
    <input type="submit" value="submit">

</form>

_PartialExample.cshtml

   <input type="text" name="contact" >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.