I'm new to ASP.NET MVC. I'm currently using ASP.NET MVC 3. I'm trying to create a basic form with an image button that posts data back to the controller. My form looks like the following:
MyView.cshtml
#using (Html.BeginForm())
{
#Html.TextBox("queryTextBox", string.Empty, new { style = "width:150px;" })
<input type="image" alt="Search" src="/img/search.png" value="Search" name="ExecuteQuery" />
}
MyController.cs
public class MyController: Controller
{
public ActionResult Index()
{
ViewData["CurrentDate"] = DateTime.UtcNow;
return View();
}
[HttpPost]
public ActionResult ExecuteQuery()
{
if (ModelState.IsValid)
{
return View();
}
}
}
I have verified that I'm accessing my controller code. The way I've been able to do this is by successfully printing out the "CurrentDate" associated with the ViewData. However, when I click my image button, I was assuming that my break point in the ExecuteQuery method would fire. It does not. What am I doing wrong? How do I do a simple POST in MVC?
Your form is pointing to the wrong action.
Calling Html.BeginForm() creates a <form> that POSTs to the current action (Index).
You need to pass the action name to BeginForm.
Try this one
#using (Html.BeginForm("ExecuteQuery", "MyController", FormMethod.Post))
{
#Html.TextBox("queryTextBox", string.Empty, new { style = "width:150px;" })
<input type="submit" value="Search" />
}
In your controller
public class MyController: Controller
{
public ActionResult Index()
{
ViewData["CurrentDate"] = DateTime.UtcNow;
return View();
}
[HttpPost]
public ActionResult ExecuteQuery(string queryTextBox)
{
if (ModelState.IsValid)
{
// DO SOMETHING WITH queryTextBox
return View();
}
}
}
If the image submit button is very important for you, you can still change the button background image using CSS.
Related
MODEL
public class SearchTerm
{
[Required(ErrorMessage="please enter")]
public string SearchTrm { get; set; }
}
View
#using (#Html.BeginForm())
{
#Html.ValidationSummary();
#Html.AntiForgeryToken();
....
#Html.TextBoxFor(m=>m.SearchTrm)</span>
<input type="submit" value="Search"/>
#Html.ValidationMessageFor(m=>m.SearchTrm)
#using (Html.BeginForm("Search","Home"))
{
#Html.DropDownList("SelectedFieldId", new SelectList(Model.Fields, "FieldID", "NiceName", Model.SelectedFieldId));
}
}
controller
[HttpPost]
public ActionResult Search(SearchTerm Model)
{
// some code here....
}
When i click a empty search I want the validation message to take place but instead page is getting postback and i am having NullReferenceException
Mention the script name, #section scripts { ...} and check whether jqueryval has 2 files - ~/scripts/jquery.validate.min.js","~/scripts/jquery.validate.unobtrusive.min.js","~/scripts
I have a partial view and the corresponding controller which looks as follows:
public class SearcherController : Controller
{
SearcherViewModel searcherVM;
//
// GET: /Searcher/
public PartialViewResult Index()
{
searcherVM = new SearcherViewModel();
return PartialView("_SearcherPartial", searcherVM);
}
public ViewResult Search(FormCollection formCollection)
{
return View();
}
}
On the master page I render the partial view as follows:
#{Html.RenderAction("Index","Searcher");}
In my partial view I have a form with some inputs. Form SHOULD call Search action in the Searcher controller:
#using (Html.BeginForm("Search", "Searcher"))
{
...some inputs
<input type="submit" value="SEARCH" />
}
However when I click on the "SEARCH" button, the "Index" action of the SearchController is called. What am I doing wrong?
I've noticed that with jQuery Mobile, if an anchor tag's href is the same as the current URL, the page does not refresh, as it does normally. I'm using a Stepped Wizard through a series of pages, and the final page has a link to repeat the process; this works fine except in jQuery Mobile. I'm new to the Mobile framework, so I'm not sure what events are firing that I need to hook into. Any help would be appreciated.
Here's a glimpse of the controller/ view code:
Controller:
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (ModelState.IsValid)
{
switch (model.SubmitButton)
{
case Buttons.Review:
return Review(model);
case Buttons.Confirm:
return Confirm(model);
}
}
return View(model);
}
public ActionResult Review(MyViewModel model)
{
return View("Review", model);
}
public ActionResult Confirm(MyViewModel model)
{
if (ModelState.IsValid)
{
return View("Confirm", model);
}
return View("Index", model);
}
View:
<div>
#* display stuff *#
#Html.ActionLink("Do it again!", "Index", "MyController", new { area = "MyArea" }, new { data_role = "button" })
#* display more stuff *#
</div>
Hmm, the code you posted is not javascript and for sure not using JQM..... Is that your aspx code-behind?
Either way, you'll probably want to disable JQM's ajaxEnabled loading if you want to reload the whole page in the current browser window.
See documentation
i have designed a view in asp .net mvc3 off course registration form. This is very simple form having name ,father name , qualification and a submit button , after pressing submit button i want to display information by using another view. please suggest me how can i send information from one view to another view.
my controller class is :
namespace RegistrationForm.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// ViewBag.Message = "Welcome to ASP.NET MVC!";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
return View();
}
}
}
my view is :
#{
Layout = null;
}
registrationView
Enter Name
</td>
<tr>
<td>
Enter Father Name
</td>
<td>
<input type="text" name="fname" id="fname" />
</td>
<tr>
<td>
Enter Qualification
</td>
<td>
<input type="text" name="qly" id="qly" />
</td>
</tr>
</table>
<input type="submit" value="submit" />
</div>
well, we faced this problem before, and the best way to get this to work was to define a model that this page will work with, then use this model object when posting back, or redirecting to another view.
for your case, you can simply define this model in your Models folder
ex: RegistrationModel.cs file, and define your required properties inside.
after doing so, you will need to do 2 more steps:
1- in your GET action method, create a new RegistrationModel object, and provide it to your view, so instead of:
return View();
you will need something like:
var registrationModel = new registrationModel();
return View(registrationModel);
2- Use this model as a parameter in your POST Action method, something like
[HttpPost]
public ActionResult registrationView(RegistrationModel model)
{
// your code goes here
}
but don't forget to modify the current view to make use of the provided model. a time-saver way would be to create a new dummy View, and use the pre-defined template "Create" to generate your View, MVC will generate the properties with everything hooked up. then copy the generated code into your desired view, and omit any unneeded code.
this is a Pseudo reply. if you need more code, let me know
<% using Html.Form("<ActionName>") { %>
// utilize this HtmlHelper action to redirect this form to a different Action other than controller that called it.
<% } %>
use ViewData to store the value.
just remember that it will only last per one trip so if you try to call it again, the value would have been cleared.
namespace RegistrationForm.Controllers { public class HomeController : Controller { public ActionResult Index() { // ViewBag.Message = "Welcome to ASP.NET MVC!";
ViewData["myData"] = "hello world";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
// get back my data
string data = ViewData["myData"] != null ? ViewData["myData"].ToString() : "";
return View();
}
}
And you can actually usethe ViewData value on the html/aspx/ascx after redirect to the registrationView.
For example on the registrationView.aspx:
<div id="myDiv">
my data was: <%= ViewData["myData"] %>
</div>
You could simply in you method parameter list declare the parameters with the name of the controls. For example:
The control here has an id "qly"
<input type="text" name="qly" id="qly" />
Define your method parameter list as following:
public ActionResult YourMethod(string qly)
{
//simply pass your qly to another view using ViewData, TempData, or ViewBag, and use it in the desired view
}
You should use TempData which was made exactly for it, to persist values between actions.
This example is from MSDN (link above):
public ActionResult InsertCustomer(string firstName, string lastName)
{
// Check for input errors.
if (String.IsNullOrEmpty(firstName) ||
String.IsNullOrEmpty(lastName))
{
InsertError error = new InsertError();
error.ErrorMessage = "Both names are required.";
error.OriginalFirstName = firstName;
error.OriginalLastName = lastName;
TempData["error"] = error; // sending data to the other action
return RedirectToAction("NewCustomer");
}
// No errors
// ...
return View();
}
And to send data to the view you can use the model or the ViewBag.
i have a button on the cshtml view..its clicked every-time an item is scanned.
The user has to do it one by one and once all the items have been scanned..i want to opem/pop up a new window plus redirect him to another page.. The condition whether it was the last item..is being checked in the controller method.
How can i call a javascript to open the new window from the controller..right before my 'redirecttoaction' ?
is there a better way to do it?
Here's a sample pattern:
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO Process the scanned code model.Code
if (IsLastItem())
{
model.IsLast = true;
}
return View(model);
}
and inside the view:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(x => x.Code)
<input type="submit" value="OK" />
}
<script type="text/javascript">
#if (Model.IsLast)
{
<text>
window.open('#Url.Action("foo")', 'foo');
window.location.href = '#Url.Action("bar")';
</text>
}
</script>
Its not clean to call JavaScript from controller. Instead, move the logic of checking if its a last item to the client side and call appropriate controller action as appropriate.