#using (Html.BeginForm("sendcode", "Home", FormMethod.Post))
{
<div class="selected">You Selected:</div>
<div class="sname">#ViewBag.selectsong</div>
<div class="enter" style="width:458px;height:37px; text-align:left;">
<div class="selected">Enter your mobile number</div>
<div class="mobileno">
<div><div class="spann">+91</div><input name="MNumber" type="text" class="mobileinput"/></div></div>`enter code here`
<div class="confirm"><input name="" type="button" class="confirmb"value="Confirm"onclick="location.href='#Url.Action("getdetail", "Home" )'/>
</div>
<div class="applicablee">* charges applicable as per your mobile operators</div>
</div>
}
I want to use textbox value and ViewBag value on my controller method which has been defined below?
public string getdetail(string Mnumber, string sSongName)
{
string ss = Mnumber;
string ss1 = sSongName;
return ss;
}
viewbag is a one way property
if you want to return it value you must define your variable as a property of your model
then pass the model as a parameter to your action
If you want to fill your textbox with ViewBag value try this;
<input type="textbox" id="aa" name="aa" value="#Viewbag.X"/>
If you want to pass that value use hidden method Satpal mentioned about.
Related
I have a string in the controller which queries Rest API stores the response
string rmID = searchLogic.GetRoomID(rmName.Substring(0, rmName.IndexOf(' '))).Result;
This field is not in the Model class. I need to check if the string rmID is Empty or Null in the Index.cshtml and show/hide a div class
#{
if (String.IsNullOrEmpty(rmID))
{
<div class="row" style="padding-bottom:2rem">
<div class="col-md-9" style="margin-left:auto;margin-right:auto;text-align:center">
<b>
**You have selected not valid room**
</b>
</div>
</div>
}
}
But the above one doesnot work
Use ViewBag to pass the value of rmID from controller to the View.
string rmID = searchLogic.GetRoomID(rmName.Substring(0, rmName.IndexOf(' '))).Result;
ViewBag.Id = rmID;
Then in the view, Use #ViewBag.Id to receive the value and do judgement.
View
#if (!String.IsNullOrEmpty(#ViewBag.Id))
{
<div class="row" style="padding-bottom:2rem">
<div class="col-md-9" style="margin-left:auto;margin-right:auto;text-align:center">
<b>
**You have selected not valid room**
</b>
</div>
</div>
}
I want to call a specific Action with a parameter that corresponds to the the selected element in a tag.
The Model of the View can be simplified as follows:
public class Model
{
public string SelectedElement {get; set}
public List<SelectListItem> Elements { get; set; }
}
That i'm trying to display in the View:
<h2>Info</h2>
<div class="row">
<div class="form-group row">
<label for="selector-info" class="col-sm-2 col-form-label">Elements</label>
<div class="col-sm-10">
<select id="selector-info" asp-for="#Model.SelectedElement " asp-items="#Model.Elements">
</select>
</div>
</div>
</div>
<div class="row">
<a class="btn btn-primary"
asp-controller="Info"
asp-action="Export"
asp-route-element="#Model.SelectedElement ">
Exportar
</a>
</div>
And the action in the controller:
[Route("export/{element}")]
public async Task<IActionResult> Export(string element)
{
// Do something with the data
return RedirectToAction("Info");
}
Here what I'm trying to do is to call this specific Action that accepts a parameter, and fill it with the selcted element in the tag
But the generated HTML href was incorrect, and debugging I found out that the value Model.SelectedElement was not beeing set correctly.
On the other hand if I wrap this code inside a form and change the link to a button it works. My problem with this is that I'll have multiple buttons (at least 2) that will do different actions but in all cases the selected value of the tag must be passed when the button is clicked.
Is there a way to achieve this? I know I can get the value through JavaScript but I'm trying to find a way to do this directly in ASP without JS.
I am very new to MVC , and trying to learn from videos given for MVC. In one of the video i have gone through the use of Tempdata. In the video they have shown created action result with HTTPPOST and pass data from textbox to controller and then to view using Tempdata . I have tried to practice the same . But i am not getting value from textbox,always returning as null. Below is my code,
Controller as below,
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(string name)
{
TempData["uname"] =name;
return RedirectToAction("GetUser");
}
public ActionResult GetUser()
{
return View();
}
View for Create as below,
#{
ViewBag.Title = "Create";
}
<h2>Create New User</h2>
#using (Html.BeginForm())
{
<div>
<p>Enter your name : <input type="text" id="id" placeholder="Enter username"/></p>
<p><input type="submit" id="btnSubmit" value="Create"/></p>
</div>
}
View for GetUser,
#{
ViewBag.Title = "GetUser";
}
<h2>GetUser</h2>
<div>
<h3>Welcome #TempData["uname"].ToString()</h3>
</div>
When i enter value in textbox and press button id parameter in Create action is null. Also i have not created any model class, as in video they have just shown as above code. Please give me some suggestions.
Regards
Sangeetha
if you are not using any model to send the data across , you should provide your textbox with a name attribute and that name attribute must match on the controller action , change your create view text box as shown
#using (Html.BeginForm())
{
<div>
<p>Enter your name : <input type="text" name="name" id="id" placeholder="Enter username"/></p>
<p><input type="submit" id="btnSubmit" value="Create"/></p>
</div>
}
I have added the name attribute to the text box
When you are passing values from view to controller by using input type=submit then you must set name attribute to the input elements,then you need to mention that name in method argument.
<input type="text" name="txtname" id="txtname" placeholder="Enter username"/>
<input type="submit" id="btnSubmit" value="Create"/>
Note : It will only work with input type="submit", it won't work with input type="button"
you don't need bind the Tempdata value with .ToString(). you can directly bind with #TempData["uname"]
I have a parameterless Index for the HttpGet which works. But when I post it the HttpPost version of Index is invoked and the viewmodel object is passed in, but there is only the value of the dropdown in it. The rest is null (products, title)
[HttpPost]
public ActionResult Index(ProductsViewModel pvm)
{
// breakpoint on line 36, shows that pvm.Title is null and Products too.
return View(pvm);
}
My compilable and running example can be downloaded from my OneDrive http://1drv.ms/1zSsMkr
My view:
#model KleinKloteProductOverzicht.Models.ProductsViewModel
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect"})
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#foreach (var item in Model.Products)
{
#Html.DisplayFor(i => item.Name);
}
</div>
}
}
If I have this view model:
public class ViewModel
{
public string Name {get;set;}
public string SelectedLocation {get;set;}
public IEnumerable<SelectListItem> Locations {get;set;}
}
And your actions look like this:
public ActionResult MyForm()
{
var vm = new ViewModel
{
Locations = context.Locations.ToList() // Some database call
}
return View(vm);
}
[HttpPost]
public ActionResult MyForm(ViewModel vm)
{
vm.Locations // this is null
}
It is null because the model binder can't find a form control that is setting its data.
The <form> must set some data in the view for the model binder to pick it up.
<form>
Name: <input type="text" id="name" />
</form>
This will set the Name property on the view model, because the model bind can see the id of the form control and uses that to know what to bind to.
So in terms of your view, you need to make sure you wrap any content that you want to post back to the server with #using(Html.BeginForm())
Anyway this is my guess.
Well, you seem to be confused as to how [HttpPost] and form tags interact with eachother.
You see, when .NET MVC binds your parameters in your controller actions, it tries to derive that data from the request. For [HttpGet] it does this by looking at the query string.
For [HttpPost] calls, it also looks at the Request.Form. This variable is populated with the values of all input fields that were inside the form you submitted.
Now, this is your view:
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect" })
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#foreach (var item in Model.Products)
{
#Html.DisplayFor(i => item.Name);
}
</div>
}
}
You only have one select tag (generated by Dropdownlistfor) but no other inputs. That's why .NET MVC cannot infer any other data for your view model.
If you change your view to this:
#model KleinKloteProductOverzicht.Models.ProductsViewModel
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect" })
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#for (var i = 0; i < Model.Products.Count; i++)
{
#Html.DisplayFor(model => model.Products[i].Name)
#Html.HiddenFor(model => model.Products[i].ID)
}
</div>
}
}
You'll see I've added a hidden input (<input type="hidden">) for the product id. Note that the product name still will be null.
I would suggest you follow a tutorial on .NET MVC and read up on some of the concepts behind it, because the very fact that you ask this question reveals that you have much to learn.
Best of luck!
P.S. One last tip: #Html.Blablabla writes directly to your view. You usually don't need that ";" at the end, because it will be inside your generated html.
Your property is not associated with a "postable" control, therefore it will not be submitted along with the form data. If your really want to get the value in your Title property, just set it as a hidden input.
#Html.HiddenFor(m => m.Title)
A label will not be posted when submitting a form but an input will. This is exactly what HiddenFor does; it creates a hidden input element which will be picked up by the form submit.
I am new to MVC so please bear with me.
I am trying to send a string from a textbox to a controller method so I can find an object in a database. However, I do not know how to send the string successfully from the view to the controller in a HttpGet request (only in HttpPost)
The code in my view
<div>
<label>Email</label>
#Html.TextBox("email")
</div>
<div class="btn btn-success">
#Html.ActionLink("Edit RSVP", "Edit")
</div>
The ViewResult method in my controller
// Problem is the email parameter is always null
[HttpGet]
public ViewResult Edit(string email)
{
// If the email the typed is find, it will display their contents on to a RsvpForm view
return View("RsvpForm", guestRepository.Find(email));
}
Anyone know how I can send this string through, I would be grateful.
Thanks
Like this:
#using (Html.BeginForm("Edit", "ControllerName", FormMethod.Get))
{
<div>
<label>Email</label>
#Html.TextBox("email")
</div>
<div class="btn btn-success">
<input type="submit" value="Edit RSVP" />
</div>
}
Note: I can't tell from your description whether or not you are trying to do this without reloading the page. This option will post the page to the controller, so you will get a page reload.
If you want this to load without posting the page, you can look into Ajax.BeginForm. Here is a StackOverflow article with a decent primer on the AJAX form.
update
For your example, you may could do something like this if you want to use AJAX. This is all untested, but may be close to what you would need.
First you can create a partial view that represents the user data that you want to display:
RsvpForm.cshtml
#model GuestData
<div class="hdr">Name</div>
<div class="value">#Model.Name</div>
<div class="hdr">Email</div>
<div class="value">#Model.Email</div>
Then you want to make sure that your controller returns the partial view based on the email that is sent via the GET:
GuestDataController.cs
[HttpGet]
public ActionResult Edit(string email)
{
// If the email the typed is find, it will display their contents on to a RsvpForm view
return PartialView("RsvpForm", guestRepository.Find(email));
}
Then you create the AJAX form to submit the request via a GET and load the partial view without reloading the page: view.cshtml
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("Edit", "GuestData", null, new AjaxOptions { UpdateTargetId = "UserData", HttpMethod = "Get" }, null))
{
<div>
<label>Email</label>
#Html.TextBox("email")
</div>
<div class="btn btn-success">
<input type="submit" value="Edit RSVP" />
</div>
}
<div id="UserData"></div>
The easiest way to do it is to create a form as follow :
#using(Html.BeginForm("Edit", ControllerName, FormMethod.GET))
{
#Html.Label("Email")
#Html.TextBox("email")
<input type="submit" value="Edit RSVP"/>
}
or you can use Jquery to change the link when textbox value change (which I do not recommend):
$('input[name=email]').on('change' function()
{
var value = $(this).val();
var href = $('.btn').next('a').attr('href');
href += '?email='+value;
$('.btn').next('a').attr('href', href)
});