Ajax.BeginForm() is this then MvcAjax or Jquery?
By default it is jquery. You need to reference the jquery.unobtrusive-ajax.js
script for this to work.
Or would I use Html.BeginForm() and register something like $.post on the click event of the Form.
That's an alternative. Personally that's what I do.
I assume that it is correct, that I am posting to the create action of the commentscontroller and I would use the JsonModelBinder to transform it to a model. After that I would return Json and would append it to my comments list...
The JsonModelBinder has been introduced in ASP.NET MVC 3 and it allows you to send a JSON string to a controller action which will be mapped back to a view model. For example if you have the following view model:
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
and the following action:
public ActionResult Foo(PersonViewModel person)
{
...
}
the traditional way to invoke it in AJAX is:
$.ajax({
url: '@Url.Action("foo")',
type: 'POST',
data: { name: 'john', age: 20 },
success: function(result) {
// TODO:
}
});
and in ASP.NET MVC 3 you could send a JSON as request parameter which will be bound to the PersonViewModel
action parameter:
$.ajax({
url: '@Url.Action("foo")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: 'john', age: 20 }),
success: function(result) {
// TODO:
}
});
You don't use a file input control. Server side controls are not used in ASP.NET MVC. Checkout the following blog post which illustrates how to achieve this in ASP.NET MVC.
So you would start by creating an HTML form which would contain a file input:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
and then you would have a controller to handle the upload:
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
Best Answer
The correct way is to only have one form. Then use AJAX to populate the cascading drop down list. The are 100s of examples online how to do this with JSON