简体   繁体   中英

Using C# MVC multiple dynamic models in View

I have a View with several form that I'm using for searching and displaying the results as partial View in like SearchByNumber, SearchByVehicle, etc.

I'm trying to load view and execute search for different forms by posting link with querystring like www.example.com/Search?number=101010 from different view.

For the first form, SearchByNumber I only have one parameter, string number and i'm returning view with dynamic Model and its working like it should, but I only manage to make search for this form.

Here is my controller:

public ActionResult Index(string number)
{
  return View(model: number);
}

and in the View I have:

<form id="searchbynumberform">
    Search By Any Number:
    <div class="input-group input-group-sm">
        <input type="text" class="form-control" name="number" id="number" value="@Model">
        <span class="input-group-btn">
            <button class="btn btn-primary" type="button" name="numbersearch" id="numbersearch" disabled>
                Search
            </button>
        </span>
    </div>
</form>

My Question is, if anyone can help me, How to perform search let's say on the second form where I have int type and string name parameters?

Thank You in advance...

At the moment your Model is only the search string that was entered , which seems rather incomplete. It would make a lot more sense if the Model also contained the actual search results , which after all is what the user wants to see. And then you can also add the other search properties.

The MVC approach for this is to create a (View)Model class, somewhere in your project, something like this:

public class SearchModel
{
    public string Number { get; set; }
    public int? Type { get; set; }
    public string Name { get; set; }
    public List<SearchResult> SearchResults { get; set; }
}

And then use it eg like this:

public ActionResult Index(string number)
{ 
    var model = new SearchModel
    {
        Number = number,
        SearchResults = GetByNumber(number)
    };
    return View(model);
}

public ActionResult IndexOther(int type, int name)
{
    var model = new SearchModel
    {
        Type = type,
        Name = name,
        SearchResults = GetByTypeAndName(type, name)
    };
    return View(model);
}

And in your Index.cshtml :

@model SearchModel

@* You can now use Model.Number, Model.Type, Model.Name and Model.SearchResults. *@

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM