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?
CodePudding user response:
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...
}
CodePudding user response:
Actually you can send your model if you use HtmlTagHelper like this
@model List<Models.MyModel>
@Html.Partial("MyPartialName",@Model)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Absolutely you have to send your model from controller like this
public IActionResult Index()
{
.....
....
return View(MyModel);
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
you must create your partial .cshtml in Share folder. This is important
CodePudding user response:
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" >