I have created a very simple view in my MVC3 project that contains a textbox that receives and validates a URL. The controller class is rather simple:
[HttpPost]
public ActionResult Save(ValidationModel model)
{
if (ModelState.IsValid)
{
//Save or whatever
}
return View(model);
}
I'm needing some guidance on how to retrieve the URL entered into the textbox, and subseuquently scan the resulting page for hyperlinks or tags. Once those tags are scanned, I need to return a new view to my user with a list or grid of the tags in alpha order.
Can anyone point me in the correct direction on above steps?
Thanks:)
In your view model you will have a property:
public class ValidationModel
{
[Required]
public string Url { get; set; }
}
and then you will have a corresponding textbox in the view:
#model ValidationModel
#using (Html.BeginForm)
{
#Html.EditorFor(x => x.Url)
<button type="submit">OK</submit>
}
and finally in your POST controller action:
[HttpPost]
public ActionResult Save(ValidationModel model)
{
if (ModelState.IsValid)
{
//Save or whatever
// use model.Url here => it will contain the user input
}
return View(model);
}
Try this:
in your view where your using your model inside your FORM:
#Html.TextBoxFor(m => m.MyHyperLink)
and in your controller you do this:
model.MyHyperLink you can manipulate the string or do what ever you want
easy as that..
hope i helped.
Related
I am using EF4 (Db First) and I have an entity with a number of non-nullable properties.
In an Edit form (Razor/MVC3), I want to allow the editing of only one of the properties, but not the others.
To get this to work, I am having to put #Html.HiddenFor(...) statements for each of my other properties that can't be nullable, otherwise I get an error on SaveChanges().
Is there a simple way to just have the ID hidden on the view, the property that can be edited, and then update ONLY that property?
All you need to do in this case is to include the ID of the entity you are editing as a hidden field as well as a text field for the property that you actually wanna edit:
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.ID)
#Html.EditorFor(x => x.PropertyYouWannaEdit)
<button type="submit">Update</button>
}
and then in the corresponding controller action you could retrieve the entity that needs to be edited from your database, update the value of the property that needs editing and save back the changes.
[HttpPost]
public ActionResult Update(SomeEntity model)
{
SomeEntity entityToEdit = db.GetEntity(model.ID);
entityToEdit.PropertyYouWannaEdit = model.PropertyYouWannaEdit;
db.Update(entityToEdit);
return RedirectToAction("Success");
}
But personally I would use a view model and AutoMapper to handle this situation. So I would start by designing a view model representing the requirements of my view and including the properties that needs to be edited only:
public class MyEntityViewModel
{
public int ID { get; set; }
public string Property1ToBeEdited { get; set; }
public string Property2ToBeEdited { get; set; }
...
}
and then have the corresponding view:
#model MyEntityViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.ID)
#Html.EditorFor(x => x.Property1ToBeEdited)
#Html.EditorFor(x => x.Property2ToBeEdited)
...
<button type="submit">Update</button>
}
and finally the 2 controller actions (GET and POST):
public ActionResult Update(int id)
{
// Fetch the domain model that we want to be edited from db
SomeEntity domainModel = db.GetEntity(id);
// map the domain model to a view model
MyEntityViewModel viewModel = Mapper.Map<SomeEntity, MyEntityViewModel>(domainModel);
// pass the view model to the view
return View(viewModel);
}
[HttpPost]
public ActionResult Update(MyEntityViewModel model)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay view so that the user can fix the errors
return View(model);
}
// fetch the domain entity that needs to be edited:
SomeEntity entityToEdit = db.GetEntity(model.ID);
// update only the properties that were part of the view model,
// leaving the others intact
Mapper.Map<MyEntityViewModel, SomeEntity>(model, entityToEdit);
// persist the domain model
db.Update(entityToEdit);
// we are done
return RedirectToAction("Success");
}
I am doing the ASP.net MVC 3 (Empty type and not the internet type) with the Database First approach...
What i need is
Step 1:
I just used the dropdown to display the various locations where the company is located. The list comes from the Organization table and Location is only one string field in this Oranization Table,
Step 2:
While the user is doing registration, the dropdown list will show the locations.. Now, user selects India, then this value (Location Name) should store in the UserLogin Table...
Now how to read the value from the dropdown and i hope you understand my question and thanks in advance
I would use view models:
public class RegisterViewModel
{
public string LocationName { get; set; }
public IEnumerable<SelectListItem> Locations { get; set; }
}
then a controller action that will serve the view:
public ActionResult Index()
{
var model = new RegisterViewModel();
model.Locations = new SelectList(dbcontext.Organization_Details, "OName", "OLocation");
return View(model);
}
then the corresponding strongly typed view:
#model RegisterViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.LocationName)
#Html.DropDownListFor(x => x.LocationName, Model.Locations)
<button type="submit">OK</button>
}
and finally the controller action that will be invoked when the form is submitted:
[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
// model.LocationName will contain the selected location here
...
}
I have a view where everything will be populated by the user - but relates to a parent entity. I pass that Id to my view using ViewBag, but I don't know how to get it back to the post action in the controller. I have tried hidden form fields, but it isn't showing in the post, or I do not know how to grab it...
Controller:
public ActionResult AddCar(int id)
{
ViewBag.Id = id;
return View();
}
View (tried):
#using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = carId }))
{
View (tried):
#Html.Hidden(carId.ToString())
HOw do I retrieve the value in my post action in my controller? Or is there a better/different way to approach it?
THanks
Create a ViewModel for post, it would be as follows
public class Post
{
int id {get;set;}
//other properties
}
and in your controller action send a post object
public ActionResult AddCar(int id)
{
Post post = new Post();
post.Id = id;
return View(post);
}
your view should use the Post class as the model
#model namespace.Post
#using (Html.BeginForm("AddReturn", "DealerAdmin", FormMethod.Post)
{
#Html.HiddenFor(model => model.Id)
}
and your controller action which expects result should have a post object as the input parameter
public ActionResult AddReturn(Post post)
{
//your code
}
The hidden field should works. The problem is that your controller did not accept it.
You can use ViewModel to achieve this. Or, use the code below in your action:
id = Request.Form["id"]
Try like this:
#using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = ViewBag.Id }))
{
...
}
there some way
1. send the value with query string if there is only one value to send to the controller
2. if you want collect many field from view you can use formcollection
sample::
public actionresult method1()
{
int id = //everything you want
viewbag.id=id;
....
//and other field to collect
}
in view
<form method="post" action="method1" enctype="now i dont remeber the value of this option" >
#html.hidden("id")
.....
<input type="submit" value"Send"/>
</form>
[httpPost]
public actionresult method1(fromcollection collection)
{
int id = collection.get("id");
....
//and other field to collect
}
I send a BOOKVIEWMODEL with fields and a simple IEnumerable in view I get the this list IEnumerable in the view by a method with JSON AJAX in view and I fill my table Ristourne(View) with JQUERY it works very well but I not know how I fill (BIND or refresh) the list IEnumerable of my BOOKVIEWMODEL in the VIEW to recovered it in the Controller:
[HttpPost]
public ActionResult Create(BookViewModel _bookViewModel)
{
if (ModelState.IsValid)
{
_bookViewModel.Ristourne
return RedirectToAction("Index");
}
return View(_bookViewModel);
my bookviewmodel
public class BookViewModel
{
public String book { get; set; }
public String price { get; set; }
public IEnumerable<Ristourne> Ristourne { get; set; }
}
For the model binding to work, you need to "mimic" the convention MVC uses when generating the form fields.
I don't know the contents of the Ristourne class, but let's say it had 1 field called Foo.
In that case, when you render out the elements (from the JSON AJAX callback), make them look like this:
<input type="text" name="Model.Ristourne[0].Foo" id="Model.Ristourne[0].Foo"/>
<input type="text" name="Model.Ristourne[1].Foo" id="Model.Ristourne[1].Foo"/>
<input type="text" name="Model.Ristourne[2].Foo" id="Model.Ristourne[2].Foo"/>
And so on. Easiest thing to do is in your AJAX callback, just use a basic for loop to create the elements indexer.
Altenatively, a cheat/easy way around this problem would be to make your AJAX action return a PartialViewResult:
public PartialViewResult Book()
{
var ristournes = _repo.Get();
var model = new BooksViewModel { Ristourne = ristournes };
return PartialView(model);
}
Then the partial view:
#Html.EditorFor(model => mode.Ristourne)
Then MVC will create the form fields correctly.
I always prefer this option over dynamically generated form fields. If you want to go down this path often, you should consider something like Knockout.js and/or Upshot.
I have a view model that contains an object containing a list and I'm outputting this list using a WebGrid.
The page can currently postback to multiple Actions which edit/add to this list. I'd like to persist this data across all postbacks so all Actions can act upon any changes past Actions have performed on the list. Is there anyway I can get the webgrid to bind to my model in the controller? Or am I required the list using another method like session/database?
Here's my code to help clear up what I mean.
I have a view model looking like this:
public class EggBasketViewModel {
public Basket EggBasket { get; set; } // Contains list of eggs & other basket info
public Egg EggToAdd { get; set; }
}
and I'm outputting it like this:
#model Basket.Models.EggBasketViewModel
#{
var grid = new WebGrid(Model.Eggs); // Eggs is my list of eggs
}
#using (Html.BeginForm()) {
#Html.Partial("_CreateOrEditEggBasket")
#Html.Partial("_CreateOrEditEgg")
#grid.GetHtml()
<p>
<button name="button" value="submitEgg">Add Egg</button>
<button name="button" value="submitBasket">Submit Basket</button>
</p>
}
With my controller looking like so:
[HttpPost]
public ActionResult Create(EggBasketViewModel Model, string button)
{
if (ModelState.IsValid) {
switch (button) {
case "submitEgg":
return this.submitEgg(Model);
case "submitBasket":
return this.submitBasket(Model);
default:
break;
}
} else {
return View();
}
}
public ActionResult SubmitBasket(EggBasketViewModel Model) {
eggBasketRepository.InsertOrUpdate(Model.EggBasket);
eggBasketRepository.Save();
return RedirectToAction("Index");
}
public ActionResult SubmitEgg(EggBasketViewModel Model) {
Model.EggBasket.Eggs.Add(Model.EggToAdd);
return View(Model);
}
I created it this way thinking the WebGrid would output data in a way the model binder would be able to bind it to my view model on POST and so persist any new Eggs using the html output by the WebGrid. Is there any way the WebGrid could output the list in a way compatible with the model binder? Or am I better off using a different method?
Thanks.