How do i pass two text inputs into ActionResult method - c#

I've been working on a large project for a few days. Its all finished except for this part. I'm trying to pass 2 text boxes into my home controller method.
I've tried to use "model." and "item." but with no luck. it always passes null
<p>
#Html.ActionLink("Display", "Home", FormMethod.Post)
</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default"> <br> <br>
</div>
}
and in the home controller is
[HttpPost]
public ActionResult Display(String Month, String Extra)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Index");
}
return view;
}
I want it to pass whatever value is typed in the textboxes when the "Add" Button is clicked but it gives null

try this,
In View
#using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default"> <br> <br>
</div>
}
In Controller,
[HttpPost]
public ActionResult Display(SomeClass someClass)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Index");
}
return view;
}
Create Normal class name SomeClass, name as per your requirment,
public class SomeClass{
public string Month {get;set;}
public string Extra {get;set;}
}
the name attribute of inputs should match to properties of SomeClass, it will map automatically, you then can access the value by using someClass object
someClass.Month and someClass.Extra

In order to correctly map to the action's parameters, you must use the name attribute.
#using (Html.BeginForm("Display", "Home"))
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default">
</div>
}
Totally unrelated, but it seems you have 2 nested forms and one of them POSTs to a php page. Is that desired?
Also, remove the following code because it does not make any sense:
<p>
#Html.ActionLink("Display", "Home", FormMethod.Post)
</p>

To add on to the previous answer, I would suggest accepting the form as a FormCollection in the controller, because the form does not seem to be tied to the model:
[HttpPost]
public ActionResult Display(FormCollection collection)
{
if (ModelState.IsValid)
{
string month = collection["Month"];
string extra = collection["Extra"];
return RedirectToAction("Index");
}
return View();
}

namespace Your.Models
{
public class DisplayModel
{
public string Month {get;set;}
public string Extra {get;set;}
}
}
[HttpPost]
public ActionResult Display(DisplayModel model)
{
if (ModelState.IsValid)
{
string month = model.Month;
string extra = model.Extra;
return RedirectToAction("Index");
}
return View();
}
#using Your.Models
#model DisplayModel
#using (Html.BeginForm("Display", "Home", new { id="displayview" }))
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default">
</div>
}

Related

How to use model data in a view?

I have HomeController and Index method:
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
}
It returns this page:
<form asp-controller="Player" asp-action="VideoPlayer" method="post">
<div class="demo-btns">
<div class="info">
<div class="buttons">
<p><input type="text" name="userName" placeholder="Name:" size="18" /></p>
<p><input type="text" name="roomCode" placeholder="Code of the room:" size="18" /></p>
<input type="submit" class="modal__trigger2" value="Join Room" />
</div>
</div>
</div>
</form>
PlayerController:
public class PlayerController : Controller
{
public static RoomData roomData = new RoomData();
public IActionResult VideoPlayer(string userName, string roomCode)
{
roomData.UserName = userName;
roomData.RoomCode = roomCode;
return View();
}
}
I'd like to show userName and roomCode on another page that is why I use PlayerController and VideoPlayer action
#using Watch.Models;
<div class="content-box-center-monitor">
<div>Model?.RoomData></div>
<div>Model?.RoomCode</div>
</div>
But it doesn't work. My final html looks like this and I don't know why:
<div class="content-box-center-monitor">
<div></div> // no data
<div></div> // no data
</div>
You need to return the model to the view
public class PlayerController : Controller
{
public static RoomData roomData = new RoomData();
public IActionResult VideoPlayer(string userName, string roomCode)
{
roomData.UserName = userName;
roomData.RoomCode = roomCode;
return View(roomData);
}
}
Then in VideoPlayer page
#model RoomData;
<div class="content-box-center-monitor">
<div>Model?.UserName</div>
<div>Model?.RoomCode</div>
</div>

Get text file as input in c# mvc

I want to get the text file as input but I am getting only null value...
public ActionResult add_content()
{
return View();
}
[HttpPost]
public ActionResult add_content(HttpPostedFileBase d)
{
return View();
}
HTML:
<form action="http://localhost:49416/g1/add_content" method="post">
<input type="file" name="d" />
<input type="submit" name=" add content" />
</form>
I have included the screenshot with breakpoint
You can try this:
Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
return View();
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file"> Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
}
You were missing the enctype = "multipart/form-data"
Also it is important to note that input name must be the same in controller.

Html.Hidden() generating blank values in HTML

I have a form on my view:
#using (Html.BeginForm("ClearData", "MemberPass", FormMethod.Post))
{
<div>
#foreach (var property in ViewData.ModelMetadata.Properties)
{
#Html.Hidden(property.PropertyName, property.Model)
}
</div>
<button>Clear</button>
}
and the following action methods:
public ActionResult Index()
{
MemberPassInfoViewModel memberPassInfoViewModel = new ServiceUtilities().GetEventDetails(DateTime.Now.Date);
return View("Index", memberPassInfoViewModel);
}
public ActionResult GetMemberPassInfo(MemberPassInfoViewModel currentMemberPassInfoValues)
{
MemberPassInfoViewModel updatedMemberPassInfoViewModel = new ServiceUtilities().GetMemberPassInfoViewModel(currentMemberPassInfoValues);
return View("Index", updatedMemberPassInfoViewModel);
}
public ActionResult ClearData(MemberPassInfoViewModel currentMemberPassInfoValues)
{
MemberPassInfoViewModel updatedMemberPassInfoViewModel = new ServiceUtilities().ClearData(currentMemberPassInfoValues);
return View("Index", currentMemberPassInfoValues);
}
In debug I can see that the model's two properties are present. However when I view the generated HTML, one of the properties has a blank value:
<input id="SearchCode" name="SearchCode" type="hidden" value="23" />
<input id="FullName" name="FullName" type="hidden" value="" />
I noticed that this could be fixed by replacing:
#Html.Hidden(property.PropertyName, property.Model)
with:
<input type="hidden" value="#property.Model" name="#property.PropertyName" />
Which generates:
<input type="hidden" value="23" name="SearchCode" />
<input type="hidden" value="Alex Robert" name="FullName" />
Why does the #Html.Hidden() method not work, but explicitly writing the <input> tag does work?

Sending a phrase (variable) from searcher (from view) to controller, asp.net mvc

I'm trying to create searcher in asp.net. I'm so green about it. I'm trying to create in view and send to controller variable, which has text written in searcher. In that moment, I have smth like that -->
My question is, where and how create and send variable and give her data written in searcher?
Layout
form class="navbar-form navbar-left" role="search">
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Wpisz frazę...">
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
</form>
Controller
public class SearcherController : ApplicationController
{
[HttpGet]
public ActionResult Index(string message)
{
ViewBag.phrase = message;
getCurrentUser();
return View();
}
}
View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
<li>#ViewBag.message</li>
</ul>
You're missing a key part of MVC -> the Model.
Let's create one first:
public class SearchModel
{
public string Criteria { get; set; }
}
Then let's update your "Layout" view (don't know why you had a form in a form?):
#model SearchModel
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
#Html.EditorFor(m => m.Criteria)
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
Then your action that serves that view:
[HttpGet]
public ActionResult Index()
{
return View(new SearchModel());
}
Then your post method would be:
[HttpPost]
public ActionResult Index(SearchModel model)
{
ViewBag.phrase = model.Criteria;
getCurrentUser();
return View();
}

Adding an item to a virtual collection ASP.NET MVC

I am trying to post an item to a collection that belongs to another model.
This is the form in the view:
#using (Html.BeginForm("Create", "Comment", FormMethod.Post, new { enctype = "multipart/form-data", encoding = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
<input type="hidden" value="#Model.DeviceID" />
<div class="form-group">
<h5>Your name</h5>
<div class="col-md-10">
<input name="Author" />
</div>
</div>
<div class="form-group">
<h5>Comment</h5>
<div class="col-md-10">
<textarea name="Comment"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" /> <!--Next</input>-->
</div>
}
and the controller code is set up as follows
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, int devID, string Author, string text)
{
string url = this.Request.UrlReferrer.AbsolutePath;
Comment comment = new Comment();
if (ModelState.IsValid)
{
//db.Comments.Add(comment);
db.SaveChanges();
return Redirect(url);
}
return Redirect(url);
}
However this doesnt work because I cant set the model id of the item that is getting posted.
What is the Asp.net MVC way to add to a virtual collection that a model owns?
What I have noticed the names don't match in your controller. So you don't retrieve it well.
Change first this line:
<input name="Author" /> and <textarea name="Comment"></textarea>
By:
<input name="author" /> and <textarea name="comments"></textarea>
Could you change the parameters to match the name from the view.
public ActionResult Create(string returnUrl, int DeviceID, string author, string comments)
{
string url = this.Request.UrlReferrer.AbsolutePath;
Comment myComment = new Comment();
comment.DeviceID = DeviceID;
comment.Author = author;
comment.Comments= comments;// I presume your Comment class has thoses properties if not you can see at least the way you can deal with that
if (ModelState.IsValid)
{
db.Comments.Add(myComment);
db.SaveChanges();
return Redirect(url);
}
return Redirect(url);
}
I hope it will help. If you can show the code of your Comment model so I can edit that if it requires.

Categories

Resources